laravel-雄辩的关系

时间:2017-02-19 07:44:44

标签: laravel eloquent laravel-5.3

我有一个课程表,一个课程hasMany部分和部分hasMany讲座和讲座hasMany评论。如果我有一个评论ID并且我想知道它的课程名称,我该如何定义LectureComment模型中的关系?

表格结构

课程:id|title

部分:id|course_id|name

讲座:id|section_id|name|description

讲座评论:id|lecture_id|user_id|comment_body

1 个答案:

答案 0 :(得分: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

希望它会有所帮助:)

相关问题