簡體   English   中英

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變量似乎在查詢中沒有表名,下面是輸出的查詢:

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);
}

您可以指定要使用的表。

$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);
});

我不知道表名到底應該是什么,因此不知道占位符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM