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

allw's avatar
Level 4

Looking to retrieve objects then nest the children

So I am looking at making a student management system,

I need to be able to retrieve the following models

Student

Result

Test

Paper

Target

Grade

Problem is that both results and targets share grades but results also a belong to multiple papers.

the relationships look something like:

Student-(M2M)-Group
Group-(O1M)-Test
Test-(M2M)-Paper
Student-(O2M)-Result
Paper-(O2M)-Result
Result-(O2M)-Grade
Student-(O2M)-Target
Target-(O2M)-Grade

is there a way to use something like

$students = Student::join('group_student', function ($join) use ($group) {
          $join->on('group_student.student_id', '=', 'students.id')
                ->where('group_id', $group->id);
        })


->with('papers.results.grade')
->whereIn('papers.id', $paper_ids)

->with('targets.grade')
->where('targets.faculty_id', $group->faculty_id)


->get();

that way in the view I could call something like:


foreach($students->papers as $paper) //obviously using blade 
{
    $paper->result->grade->name;
}

0 likes
1 reply
allw's avatar
Level 4
$students = Student::
        join('group_student', function ($join) use ($group) {
          $join->on('group_student.student_id', '=', 'students.id')
                ->where('group_id', $group->id);
        })
        ->with(['results.grade' => function ($query) use ($paper_ids) {
          $query->whereIn('results.paper_id', $paper_ids);
        }])
        ->with('targets.grade')
        ->orderBy('last_name', 'asc')->get();

This is what I have at the moment which is not returning any "Results" unfortunately without adding another table (which I would rather not do) I cannot just attach a

->with('papers.results.grade')

any ideas?

Please or to participate in this conversation.