Return 所有来自分层 belongsToMany 关系的数据 Laravel 5.3

Return all data from hierarchical belongsToMany relationship Laravel 5.3

我有 Netflix 风格的模型(在层次结构的意义上)。例如,我有一个 Lesson 属于 ToMany Course,属于 ToMany Collection,属于 ToMany Subgroup,属于 ToMany Group。 Lesson 是最低级别,Group 是最高级别。沿着链向下,每个都属于下一个 link 中的许多。

我正在使用一个过滤器按钮,该按钮将从 Wordpress 调用我的 Laravel API。当我传递组 ID 和子组 ID 时,我需要能够 return 属于子组的集合。但我需要的是:

$group->with('subgroups')->where('subgroup_id')->with('collections')->with('courses')->with('lessons');

但是,这种语法不起作用。有没有办法向下查询每个级别并获取该级别的关系?

如果需要更多代码,我很乐意分享更多。

以下内容未经测试,但希望能立即奏效,或者让您了解如何自己解决问题。

几点:

  1. 您可以在 with 调用中链接关系。例如。 courses.lessons 将获得找到的 collections 的所有 courses 和相关 lessons
  2. whereHas 允许您查询关系。在此示例中,我正在查找所有集合,其中包含与传递的子组 ID 匹配的子组,以及与传递的组 ID 匹配的组。

示例:

$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();