Laravel - Eloquent关系

3
我有一个课程表,一个课程hasMany章节和章节hasMany讲座,讲座hasMany评论。如果我有一个评论id并想知道它的课程名称,应该如何在LectureComment模型中定义关系? 表结构 courses: id|title sections: id|course_id|name lectures: id|section_id|name|description lecture_comments: id|lecture_id|user_id|comment_body
1个回答

1
在课程模型中:
public function sections()
{
    return $this->hasMany('App\Section');
}

章节模型:

public function course()
{
    return $this->belongsTo('App\Course');
}

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

讲座模式:
public function section()
{
    return $this->belongsTo('App\Section');
}

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

LecturesComment模型:

public function lecture()
{
    return $this->belongsTo('App\Lecture');
}

为了获取所需数据,您必须遍历关联关系。
如果您正确编写了外键,这段代码将返回一个课程标题:
$comment = LecturesComment::find(1);

$courseName = $comment->lecture->section->course->title

希望它有所帮助 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接