Laravel Count Vehicles W / O Images

时间:2018-10-24 18:10:50

标签: php sql laravel eloquent

我正试图获得一些帮助,以重写一些在我正在努力提高速度的项目中扔给我的东西。我正在使用 Laravel 5.4 。我可以尝试计算多少辆车没有图像而不循环通过每辆车。

每辆车的vehicle_id都会更正vimages表中的vehicle_id col。

我试图消除不必遍历每辆车并为每辆车进行单独的SQL调用的情况。

我要计数的功能:

    'missingDescription' => $inv->where('vehicle_type','=','NEW')->where('description','=', '')->where('description','=', null)->count(),

要计数的原始函数:

 'images' => $inventories->filter(function($row) {
            if ($row->Images()->get()->count() <= 0) {
                return true;
            }
            return false;
        })->count(),

        'stockphotos' => $inventories->filter(function($row) {
            return $row->Images()->get()->filter(function($item) {
                return $item->isStockPhoto && !$item->isDeleted;
            })->count() > 0 ? true : false;
        })->count(),

图片功能:

public function images() {
        return $this->hasMany('App\Vimage');
    }

2 个答案:

答案 0 :(得分:1)

您可以使用withCount。因此,当您最初获取模型时,请添加withCount('images'),该操作会将images_count附加到返回的模型中。

$inventories = Inventory::withCount('images')->get();

'images' => $inventories->where(images_count, 0)->count()

这是laravel页面,仅供参考Querying Relationship Absence

答案 1 :(得分:0)

您需要使用搜索闭包作为描述,因为您要查找的是空字符串还是null。

'missingDescription' => $inv->where('vehicle_type','=','NEW')
                              ->where(function($query) {
                                  $query->where('description','=', '')
                                     ->orWhereNull('description');
                               })->count(),
相关问题