Laravel eloquent 关系查询不起作用

Laravel eloquent relationship query does not work

我想获取所有主题为 course_id:

的测验

Topic模型具有以下功能:

public function quizzes()
{
    return $this->hasMany('App\Quiz');
}

测验模型具有以下功能:

public function topic()
{
    return $this->belongsTo('App\Topic', 'topic_id');
}

这是我的控制器函数中的代码:

$topics = Topic::with('quizzes')->whereCourseId($course_id)->orderBy('created_at', 'asc')->get();

return dd($topics->quizzes);

我收到以下 Exception 错误:

Property [quizzes] does not exist on this collection instance.

我好像不知道怎么回事?

这是因为您想获得 quizzes 个集合而不是一个模型,所以像这样遍历此集合:

foreach ($topics as $topic) {
    $topics->quizzes;  // <- this is fine :)
}

出于调试目的,您可以这样做:

dd($topics->fist()->quizzes);

第二个需求你可以这样做:

$quizzes = Quizzes::whereHas('topic', function ($query) use ($course_id) {
        $query->where('course_id', $course_id);
    })->get();