我正在使用 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`)
'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');
});
其他可以使用
whereHas
方法,例子如下:
Item::with('unit', 'stock')->whereHas('stock', function ($query) {
$query->where('stock', '<', DB::raw('items.min_stock'))
});