Hey guys I have a question about multi-relationships.
I have 3 tables:
students - id, username, pass
teachers - id, username, pass
periods - id, teacher_id, name
and student_period for many to many.
that's how the database looks: https://i.imgur.com/MXxLmQj.png
What I'm trying to do is I wanna get all students of teacher via periods, haven't seen such relationship who does that, any idea how to do such thing?
CodePudding user response:
Set the relation between teachers and periods hasMany
and belongsTo
Set the relation between students and periods as belongToMany
and belongsToMany
then you can get the students of a specific teacher like this
$teacherId = 1;
$students = Student::whereHas('periods.teacher', function($teacherQueryBuilder) use ($teacherId) {
$teacherQueryBuilder->where('id', $teacherId);
})->get();