Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

siavash1375's avatar

retrieve data from three tables

Hi I have three tables:

Teacher

id

name

family_name

ClassRoom

class_name

teacher_id

Student

name

family_name

Teacher have one to many relation with ClassRoom

Student have many to many relation with ClassRoom

how can i retrieve all Students of a Teacher?

0 likes
4 replies
Snapey's avatar

do you have primary keys on classroom and student?

if you want to find students of teacher you need a teacher_id column on the student, or, if students have many teachers then you will need a student_teacher pivot table

spodlogar's avatar
Level 29

I am assuming you want to get a Teacher's students based on the ClassRoom Model.

You will need to add a classroom_student pivot table which will allow you to get all the students in a classroom.

class ClassRoom extends Model
{
    

    public function students()
    {
        return $this->belongsToMany(Student::class);
    }
    
    public function teacher()
    {
        return $this->belongsTo(Teacher::class);
    }

}
class Teacher extends Model
{

    public function classrooms()
    {
        return $this->hasMany(ClassRoom::class);
    }
    
    public function students()
    {
        $classrooms = $this->classrooms;
        $students = $classrooms->flatMap(function($classroom){
            return $classroom->students;
        });

        return $students;
    }

}

It would probably look something like that

1 like

Please or to participate in this conversation.