2017-02-19 271 views
3

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

表结构

课程:id|title

部分:id|course_id|name

讲座:id|section_id|name|description

lecture_comments:id|lecture_id|user_id|comment_body

回答

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 

希望这会有所帮助:)