Laravel中雄辩模型的多层次关系

时间:2018-06-30 06:07:32

标签: laravel laravel-5 eloquent laravel-5.6

我想找到 $project = Project::with('tasks.tags')->whereHas('tasks', function($query){ $query->whereHas('tags', function($query) { $query->where('id', 1); }); })->get();

其中只有具有特定ID标签的项目才返回结果集中。

例如我想找到一个包含带有ID为1的任务和带有标签的任务的项目。换句话说,请过滤返回到Project-Task关系内部的任务。

我尝试了各种方法,但到目前为止都失败了。

我尝试过:

$project = Project::with('tasks.tags')->whereHas('tasks', function($query){
            $query->whereHas('tags', function($query) {
                $query->where('tag_id', 1);
            });
})->get();

并且:

public function tasks()
{
    return $this->hasMany(Task::class, 'project_id')->setEagerLoads([]);
}

这是建立关系的方式:

在Project.php

public function tags()
{
        return $this->morphToMany(Tag::class, 'taggable')->setEagerLoads([]);

}

在Task.php

{{1}}

请注意,任务和标签之间的关系是morphToMany。

有指针吗?

2 个答案:

答案 0 :(得分:3)

您还需要确定紧急加载的范围。像下面这样的东西应该起作用:

$project = Project::with(['tasks.tags' => function ($query) {
    $query->where('id', 1);
}])->whereHas('tasks', function ($query) {
    $query->whereHas('tags', function ($query) {
        $query->where('id', 1);
    });
})->get();

答案 1 :(得分:1)

Found the answer over here.

ERROR: /private/var/tmp/_bazel_KIS/224353623a09fc9ce15220928ea2f58c/external/io_bazel_rules_closure/closure/webfiles/webfiles.bzl:43:14: name 'set' is not defined
ERROR: error loading package '': Extension 'closure/webfiles/webfiles.bzl' has errors
ERROR: error loading package '': Extension 'closure/webfiles/webfiles.bzl' has errors
INFO: Elapsed time: 0.066s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (0 packages loaded)
1707035:tensorflow KIS$