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

joshblevins's avatar

Elequent Query Help

I have a table of Employees whom take classes with the following relationships

Courses Have Many Classes

Classes Have Many Completions

Completions Have One Employee

Employees Have Many Completions

What I need to display is All Required Courses in the thead (Which I have done with this query)

$courses = Classes::where('required', 1)->groupBy('course_id')->get();

The tbody should display each employee and then the last time they completed the course in the thead. I am unsure how to tie these queries together to make it cohesive. Any help appreciated.

0 likes
1 reply
Snapey's avatar

So in your relationships, I think one is wrong

I also like to write out both halves so that you remember to create both

Course hasMany Class / Class belongsTo Course

Class hasMany Completion / Completion belongsTo Course

Completion belongsTo Employee / Employee hasMany Completion

So, conventionally, all your models are Singular and capitalised (as above)

Your relationships are singular for belongsTo and plural for hasMany

Using the above, your query would be

$courses = Course::with('classes.completions.employee')->get();

then you have all courses with nested data for classes, completions and the employee

Please or to participate in this conversation.