I have models that are Netflix-esque (in the sense of hierarchy). As an example, I have a Lesson which belongsToMany Course which belongToMany Collection, which belongsToMany Subgroup, which belongsToMany Group. Lesson is the lowest level, up to Group as the top level. Going down the chain, each one belongsToMany of the next link down as well.
I am using a filter button that will make a call from Wordpress to my Laravel API. When I pass the group id and the subgroup id, I need to be able to return the collections belonging to the subgroup. But what I need is something like:
$group->with('subgroups')->where('subgroup_id')->with('collections')->with('courses')->with('lessons');
However, that kind of syntax doesn't work. Is there a way to query each level down and get that level's relationships?
If more code is needed, I'd be happy to share more.
The following is untested, but should hopefully either work immediately, or give you an idea as to how to solve the problem yourself.
A couple points:
with
call. E.g. courses.lessons
will get all courses
and related lessons
for the collections
found.whereHas
allows you to query relationships. In this example, I am looking for all collections, with a subgroup that matches the subgroup ID passed, and that also have a group that matches the group ID passed.Example:
$groupId = 123;
$subgroupId = 456;
$collections = Collection::with('courses.lessons')
->whereHas('subgroup', function ($query) ($groupId, $subgroupId) {
return $query->whereHas('group', function ($query) use ($groupId) {
return $query->where('id', $groupId);
})
->where('id', $subgroupId);
})
->get();