Eloquent 不在子查询中的关系
Eloquent relationship where not in sub-query
我有一个关系,其中我 select 所有行都基于类别,但是如果它们在子查询中,我需要排除其中的一些。
/** @var \Illuminate\Database\Query\Builder $images */
$images = $vehicle->images()
->whereIn('image_category', $website->image_categories)
->orderBy('seq', 'ASC');
$images->whereNotIn('id', static function ($q) {
return $q->select('id')
->whereIn('image_category', [0, 99])
->groupBy('seq')
->having(DB::raw('count(`seq`)'), '>', 1);
});
dd($images->toSql(), $images->getBindings());
所以上面是我的代码,几乎可以按我的意愿工作,但是 $q
变量似乎在查询中没有 table 名称,下面是输出的查询:
select
*
from
`vehicle_images`
where
`vehicle_images`.`vehicle_id` = ?
and `vehicle_images`.`vehicle_id` is not null
and `image_category` in (?, ?)
and `id` not in (
select
`id`
where
`image_category` in (?, ?)
group by
`seq`
having
count(`seq`) > ?
)
order by
`seq` asc
这是关系:
public function images()
{
return $this->hasMany(VehicleImage::class);
}
您可以指定要使用的 table。
$images->whereNotIn('id', static function ($q) {
return $q->select('id')->from('{CORRECT_TABLE_NAME_HERE}')
->whereIn('image_category', [0, 99])
->groupBy('seq')
->having(DB::raw('count(`seq`)'), '>', 1);
});
我不知道 table 名称到底应该是什么,因此是占位符。
我有一个关系,其中我 select 所有行都基于类别,但是如果它们在子查询中,我需要排除其中的一些。
/** @var \Illuminate\Database\Query\Builder $images */
$images = $vehicle->images()
->whereIn('image_category', $website->image_categories)
->orderBy('seq', 'ASC');
$images->whereNotIn('id', static function ($q) {
return $q->select('id')
->whereIn('image_category', [0, 99])
->groupBy('seq')
->having(DB::raw('count(`seq`)'), '>', 1);
});
dd($images->toSql(), $images->getBindings());
所以上面是我的代码,几乎可以按我的意愿工作,但是 $q
变量似乎在查询中没有 table 名称,下面是输出的查询:
select
*
from
`vehicle_images`
where
`vehicle_images`.`vehicle_id` = ?
and `vehicle_images`.`vehicle_id` is not null
and `image_category` in (?, ?)
and `id` not in (
select
`id`
where
`image_category` in (?, ?)
group by
`seq`
having
count(`seq`) > ?
)
order by
`seq` asc
这是关系:
public function images()
{
return $this->hasMany(VehicleImage::class);
}
您可以指定要使用的 table。
$images->whereNotIn('id', static function ($q) {
return $q->select('id')->from('{CORRECT_TABLE_NAME_HERE}')
->whereIn('image_category', [0, 99])
->groupBy('seq')
->having(DB::raw('count(`seq`)'), '>', 1);
});
我不知道 table 名称到底应该是什么,因此是占位符。