Laravel 8,其中Relation从模型中获取where值条件



我正在使用whereRelation,但我不知道如何从基本模型中获取where值条件

我试过这个代码:

Item::with('unit','stock')->whereRelation('stock', 'stock', '<', 'items.min_stock');

并在调试器中查询结果:

select * from `items` where exists (select * from `stocks` where `items`.`id` = `stocks`.`id_item` and `stock` < 'items.min_stock')

我想要的查询结果:

select * from `items` where exists (select * from `stocks` where `items`.`id` = `stocks`.`id_item` and `stock` < `items`.`min_stock`)

'tems.min_stock'它变成了一个字符串,我该如何解决这个问题?

Otherize您可以使用whereHas方法,示例如下:

Item::with('unit', 'stock')->whereHas('stock', function ($query) {
$query->where('stock', '<', DB::raw('items.min_stock'))
});

我为我的代码找到了解决方案

我这样修改我的代码,它是有效的

Item::with('unit','stock')->whereRelation('stock', 'stock', '<', DB::raw('items.min_stock'));

感谢@Vildan Bina的回答

尝试使用whereRaw

Item::with('unit','stock')->whereRelation('stock', function (Builder $query) {
$query->whereRaw('stock < items.min_stock'); // semicolon
});

最新更新