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.
Depending on what you want to do, you have different options:
Item
's of price 30 of this Facture
$facture->items()->where('price', 30);
Item
's of price 30 of one or multiple Facture
's$factures->load(['items' => fn ($query) => $query->where('price', 30)]);
Facture
's that have at least one Item
of price = 30Facture::query()->whereHas('items', fn (Builder $query) => $query->where('price', 30));
Facture
's that have at least one Item
of price = 30, but also load only those itemsFacture::query()
->with(['items' => fn ($query) => $query->where('price', 30)])
->whereHas('items', fn (Builder $query) => $query->where('price', 30));