Laravel Multiple requirements for relationship

- 1 answer

Ad

I have an Item table, Meta table and a Item_Meta table which has all meta records for Items. One Item has many Meta records.

Item_meta has the following columns: Item_id | Meta_id | Value

Lets say I have a requirements: Requirement 1 - ['Meta_id' => 1, 'value' => 'new'] Requirement 2 - ['Meta_id' => 3, 'value' => 'LCD']

I need to build a query get all items, which have meta_id with id 1 equal to new, and meta_id with id 3 equal to LCD.

So if an item does not have one of this metas (or one of metas has wrong value) it should not be returned.

Ad

Answer

Ad

You can filter your models on relation's attributes using Eloquent's whereHas() method. In your case the following code should do the trick:

$items = Item::whereHas('metas', function($query) {
  $query->where('Meta_id', 1);
  $query->where('value', 'new);
})
->whereHas('metas', function($query) {
  $query->where('Meta_id', 3);
  $query->where('value', 'LCD);
})
->get();

I assumed that your item->meta relation is called metas.

You could also use another form of using whereHas() where you provide number of matching related records. The code will be a bit more complex but it will result in less subselects in the executed query:

$items = Item::whereHas('metas', function($query) {
  $query->where('Meta_id', 1);
  $query->where('value', 'new);
  $query->orWhere(function($query2) {
    $query2->where('Meta_id', 3);
    $query2->where('value', 'LCD);
  };
}, '=', 2)
->get();
Ad
source: stackoverflow.com
Ad