【问题标题】:Laravel Count Vehicles W/O ImagesLaravel 计数车辆 W/O 图像
【发布时间】:2018-10-24 18:10:50
【问题描述】:

我正在尝试获得一些帮助,以重写一些在我正在从事的项目中扔给我的东西,以提高速度。我在 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');
    }

【问题讨论】:

    标签: php sql laravel eloquent


    【解决方案1】:

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

    $inventories = Inventory::withCount('images')->get();
    
    'images' => $inventories->where(images_count, 0)->count()
    

    这是 laravel 页面供参考Querying Relationship Absence

    【讨论】:

      【解决方案2】:

      您需要对描述使用搜索闭包,因为您正在寻找它是空字符串还是 null。

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

      【讨论】:

      • 不是我真正想要的,我正在寻找图像方面的帮助。还是谢谢你。
      猜你喜欢
      • 1970-01-01
      • 2012-07-13
      • 2021-11-05
      • 2016-09-15
      • 2021-09-06
      • 1970-01-01
      • 2020-05-08
      相关资源
      最近更新 更多