Laravel eloquent: relationship between two owner of a table

I have three tables Students, Courses and Grades.

and grade has two foreign keys: student_id and course_id and it's belong to two table.

class Grade extends Model
{
    public function student()
    {
        return $this->belongsTo('App\Student');
    }
    public function course()
    {
        return $this->belongsTo('App\Course');
    }
}

also, student and course have many grades:

class Student extends Model
{
    public function grades()
    {
        return $this->hasMany('App\Grade');
    }
}

and

class Course extends Model
{
    public function grades()
    {
        return $this->hasMany('App\Grade');
    }
}

Now, I want to make a relationship between student and course, for example for student1 I want to retrieve all courses that have a grade on it. something like this but it's not correct:

$student1->grades->course

I can simply write

@foreach($student1->grades as $grade)
      $grade->course
@endforeach

but I don't want it, I want to have ($courses as $course) in my foreach loop.

2 answers

  • answered 2019-09-12 05:07 HIR

    I suggest you need to refer https://laravel.com/docs/5.8/eloquent-relationships#has-many-through link to achieve this,

    Add hasManyThrough relation in student modal.

    public function courses()
        {
            return $this->hasManyThrough(
                'App\Course',
                'App\Grade',
                'course_id', // Foreign key on Grade table...
                'id', // Foreign key on Course table...
                'id', // Local key on Student table...
                'student_id' // Local key on Grade table...
            );
        }
    

    I'm not tested this code but, this is the way

  • answered 2019-09-12 05:45 Kevin Bui

    What about making grades table a PIVOT TABLE for a many-to-many relationship between students and courses.

    class Student
    {
        // an alternative name could be gradedCourses.
        public function courses()
        {
            return $this->belongsToMany(Course::class, 'grades');
        }
    }
    

    So you are able to access the course directly from this relationship.

    @foreach($student->courses course)
          $course->name
    @endforeach