Imagine we have a Facture
and Item
model in a one-to-many relationship. I’m using $facture->items()
or $facture->load('items')
and it works perfectly. However, when I need to use a condition on items like where('items.price', 30)
, I have no idea how to do it without DB::
. Actually, I tried to use leftJoin()
, because it has a condition on the right side of the relation, but this solution couldn’t help me.
2
Answers
it seems this is a good use case for the
whereRelation
method,you could do something like this in your query builder:
->whereRelation('items', 'price', '=', 30)
This will effectively return only the Factures that have items which prices are 30.
reference: https://laravel.com/api/10.x/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.html#method_whereRelation
Depending on what you want to do, you have different options:
Item
‘s of price 30 of thisFacture
Item
‘s of price 30 of one or multipleFacture
‘sFacture
‘s that have at least oneItem
of price = 30Facture
‘s that have at least oneItem
of price = 30, but also load only those items