Search code examples
laravelormeloquentmany-to-many

How to query from eloquent?


ERD : enter image description here

Model

  1. Student : id
  2. Course : id
  3. Student_Course (payment) : id, student_id, course_id

The relation between Student and Course is Many to Many, because of that I make another table Student_Course.

I have one question, that is Show total amount of students that enroll at least 1 course.

Please help me to find the result. I stuck on that.


Solution

  • can you please try following example:

    Model/Student.php //write relationship in your model
    
    public function courses()
    {
        return $this->belongsToMany(Course::class, 'payment');
    }
    

    and then try with following eloquent query

    $students = Student::whereHas('courses')
        ->take(10)
        ->get();