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

Randy_Johnson's avatar

Eloquent DB Help

$this->studentsTeacher = DB::table('students')
        ->join('attendances', 'students.id', '=', 'attendances.student_id')
        ->where('attendances.teacher_id', $this->teacherId)
        ->select('students.*')
        ->get();

I made the error of connecting the student to the teacher through this attendance db, I am now at a problem where I want to just call a list of students for a teacher, but of course, if there are many attendances then the student will get called again, resulting in multiple students being shown on the classroom roster table.

Now, I am not sure how to go about, is there a little work around with the DB query, or should I write another DB which will just have teacherid, studentid, or just add a teacher id on the student table. I am not sure, which would you say be the best work for solution.

0 likes
4 replies
Cobs's avatar

I assume this is a many to many relationship with a attendances intermediate table. You can create a relationship to Teacher in your your Student model then filter this way

$students = Student::whereHas('teachers', function(Builder $teacher) use ($teacher_id) {
    $teacher->where('id', $teacher_id);
})->get();

Be aware this workaround create a "where subquery" instead of a inner join so you won't have to deal with "group by" but it can cause performance issue with very large databases.

1 like

Please or to participate in this conversation.