简体   繁体   中英

Return all data from hierarchical belongsToMany relationship Laravel 5.3

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:

  1. You can chain relationships within a with call. Eg courses.lessons will get all courses and related lessons for the collections found.
  2. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM