skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search