laraveleloquenteloquent-relationship

Use condition filter after with() or load() Laravel Eloquent


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.


Solution

  • Depending on what you want to do, you have different options:

    1. Query Item's of price 30 of this Facture
    $facture->items()->where('price', 30);
    
    1. Load Item's of price 30 of one or multiple Facture's
    $factures->load(['items' => fn ($query) => $query->where('price', 30)]);
    
    1. Load only Facture's that have at least one Item of price = 30
    Facture::query()->whereHas('items', fn (Builder $query) => $query->where('price', 30));
    
    1. Load only Facture's that have at least one Item of price = 30, but also load only those items
    Facture::query()
      ->with(['items' => fn ($query) => $query->where('price', 30)])
      ->whereHas('items', fn (Builder $query) => $query->where('price', 30));