2017-02-19 272 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 

希望這會有所幫助:)