2017-02-19 15 views
3

私はコーステーブル、コースhasManyセクションとセクションhasMany講義と講義hasManyコメントがあります。 LectureCommentモデルの関係をどのように定義する必要がありますか?コメントIDがあり、そのコース名を知りたいのですが?ラヴェル - 雄弁な関係

テーブル構造

コース: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'); 
} 

、必要なデータを受信するには、あなたが歩く必要がありますth大まかな関係。

$comment = LecturesComment::find(1); 

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

はそれが役に立つことを願っています:)

:あなたは正しく外部キーを作成した場合

、このコードは、コースのタイトルを返します。