Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 8, whereRelation take the where value condition from model

i'm using whereRelation but i do not know how to take the where value condition from the base model

I have tried this code:

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

and query result in debugger :

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

The query result i wanted :

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

'items.min_stock' it become like a string, How can i solve this ?

like image 414
Johan Nes Avatar asked Sep 17 '25 20:09

Johan Nes


2 Answers

I found solution for my code

i change my code like this and it's works

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

thanks to @Vildan Bina for the answer

like image 58
Johan Nes Avatar answered Sep 19 '25 11:09

Johan Nes


Try using whereRaw

Item::with('unit','stock')->whereRelation('stock', function (Builder $query) {
    $query->whereRaw('stock < items.min_stock');
});
like image 20
Insane Skull Avatar answered Sep 19 '25 11:09

Insane Skull