3

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

1 Answer 1

1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.