首页 > 解决方案 > 使用关系结果的雄辩查询

问题描述

我需要使用关系而不是连接,因为我想在以后使用Images模型时使用它来操作数据。

因此,例如,我可以执行此操作,而使用左连接无法做到这一点:

$result->images->getMasterImage();

但是,我的主要查询需要检查是否有足够的图像,所以我需要where根据图像的图像做一个。使用关系引入这些行时可以这样做吗?还是我也必须进行左连接?

$image_categories = [ 1, 2, 3, 4, 5, 6 ];
$main->selectRaw('count(images.id) as image_count');
$main->with([ 'images' => static function ($query) use ($image_categories) {
    /** @var \Illuminate\Database\Query\Builder $query */
    $query->whereIn('image_category', $image_categories);
}]);
$main->where('image_count', '>', 6);

标签: phpeloquent

解决方案


推荐阅读