Reputation: 2896
I have a courses table, a course hasMany
sections and sections hasMany
lectures and lectures hasMany
comments. How should I define the relationship in the LectureComment
model, if I have a comment id and I want to know its course name?
table structures
courses: id|title
sections: id|course_id|name
lectures: id|section_id|name|description
lecture_comments: id|lecture_id|user_id|comment_body
Upvotes: 3
Views: 650
Reputation: 3547
In course model:
public function sections()
{
return $this->hasMany('App\Section');
}
Section model:
public function course()
{
return $this->belongsTo('App\Course');
}
public function lectures()
{
return $this->hasMany('App\Lecture');
}
Lecture model:
public function section()
{
return $this->belongsTo('App\Section');
}
public function lectures_comments()
{
return $this->hasMany('App\LecturesComment');
}
LecturesComment model:
public function lecture()
{
return $this->belongsTo('App\Lecture');
}
To receive required data, you must walk through relations.
If you have correctly written foreign keys, this code will return a course title:
$comment = LecturesComment::find(1);
$courseName = $comment->lecture->section->course->title
Hope it will be helpful :)
Upvotes: 1