1

How would I do this query in Laravel? I think I'm getting in a right tangle.

select * from `entries`
where (`id` = (
    select entry_id FROM `elements` where `content` = 'David'
));

I have an Entry model and an Element model, and eager loading works fine (i.e. if I instead did $entries = Entry::with('elements'); it works great).

I'd like to grab the entries where the elements related element's have a certain value.

My attempt grabs all the Entries, but only the elements where the query fits:

$entries = Entry::with(['elements' => function($q) use ($find){
    $q->where('content', '=', $find);
}])->get();

1 Answer 1

2

For filtering by related models you can use has(). And in this case, because you have a condition to apply, whereHas:

$entries = Entry::with(['elements' => function($q) use ($find){
    $q->where('content', '=', $find);
}])
->whereHas('elements', function($q) use ($find){
    $q->where('content', '=', $find);
})->get();

This now only eager loads the related models matching the predicate and also makes sure only entries that have at least one related model are returned.

To reduce the duplicate code you can also put the closure in a variable:

$filter = function($q) use ($find){
    $q->where('content', '=', $find);
};

$entries = Entry::with(['elements' => $filter])->whereHas('elements', $filter)->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.