O
O
Oleg Pravdin2019-01-24 16:39:52
Laravel
Oleg Pravdin, 2019-01-24 16:39:52

How to filter entities in Laravel by column pivot value?

Good afternoon. There are item and property entities, a many-to-many relationship is implemented between them with an additional pivot (I don’t know how to translate it into Russian correctly) value column - the property value for item. How to make a request through laravel's ORM to get all items whose property value is equal to the one you are looking for? Thanks in advance.
Example:

items:
id | name
1  | a
2  | b
properties:
id | name
1  | c
2  | d
item_property:
item_id | property_id | value
1       | 1           | искомое
 Нужно получить все item, у которых для property 'c' значение 'искомое'

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2019-01-24
@jazzus

In the property model to the items() relation

public function filterItems($value)
  {
    return $this->items()->wherePivot('value', $value);
  }

and then in the controller
$value = 1;
$items = Property::find(5)->filterItems($value)->get();

A
anlamas, 2019-01-24
@anlamas

$items = Item::query()
    ->whereHas('properties', function($query) {
        $query->where('item_property.value', 5);
    })
    ->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question