Home > Enterprise >  Obtain the number of students of a teacher
Obtain the number of students of a teacher

Time:03-27

I have a table of teachers. I also have a table of courses. Each teacher has a one-to-many relationship with the course (that is, each course belongs to one teacher. But each teacher can hold several courses). I also established his relationship in Laravel. I also have a student table that is related to the course table. (Each student can participate in several courses and each course can include several students). According to Laravel standards, I also wrote the interface and relation table in the model. Now I want to get the number of students of a teacher in "Teacher Controller"? And if possible, get a list of his students. How can I do this?

teacher Model

public function course(){
         return $this->hasMany(course::class);
     }

course Model

public function teacher(){         
    return $this->belongsTo(Teacher::class);     
    } 
    public function students(){
         return $this->belongsToMany(Student::class)->withPivot('start_date','cancel_date','status');     
    }

student Model

public function courses(){         
    return $this->belongsToMany(course::class)->withPivot('status','start_date','cancel_date');     
}

Thank you for your help

I tried to get the list and number of students through the course model defined in the teacher relation to the student model defined in the course model. Through this code:

public function show(Teacher $teacher)
    {
$countStudent =  $teacher->course()->get()->students();
        dd($countStudent);

}

But Laravel makes a mistake.

CodePudding user response:

You can use hasManyThrough relationship here

Teacher.php

 public function students() {
    return $this->hasManyThrough(Student::class, Course::class);
 }

in your controller

public function show(Teacher $teacher){

 $countStudent =  $teacher->students()->count();
    dd($countStudent);

}

CodePudding user response:

public function show(Teacher $teacher)
{
$countStudent =  $teacher->course()->students()->get();
        dd($countStudent);

}

You don't need to use get method in the middle

if you want to count, use count() instead of get()

  • Related