Laravel Multiple Requirements For Relationship
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.
Answer
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();
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?