I have units that relate to subjects (many units can relate to many subjects)
Are you sure of this relationship?, They way I see it 1 subject has N units and 1 unit belongs to 1 subject.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am trying to setup my migrations and relationships between various tables so that things work (and "work well" would be even better!). Perhaps I'm coming at it from the wrong angle, so any feedback would be appreciated (but be gentle as I am a Laravel novice!)
I have units that relate to subjects (any one unit can relate to a subject) and these subjects relate to grades (many subjects can relate to many grades).
------ Example 1 ------
Grade: 6
Subject: Science
Unit: Air and Aerodynamics
or
Grade: 5
Subject: Science
Unit: Electricity and Magnetism
------ Example 2 ------
Grade: 4
Subject: Math
Unit: Patterns and Relations
or
Grade: 1
Subject: Math
Unit: Patterns and Relations
I created three tables to house the corresponding data: list_grades, list_subjects and list_units
I then created a table to relate the subjects to the grades: list_grades_list_subjects which has the following schema:
ListSubject model
public function list_grades()
{
return $this->belongsToMany('App\ListGrade', 'list_grades_list_subjects');
}
With this, it looks as though I have successfully related many subjects to many grades. In my excitement I created a list_subject_list_units table to connect the two in the same fashion as above using:
ListUnit model
public function list_subjects()
{
return $this->belongsToMany('App\ListSubject', 'list_subjects_list_units');
}
However, this doesn't work. What I mean by that is if I get the unit (say, "Patterns and Relations") I don't know how to relate that to "Science" (and thusly "Grade 1") (keeping in mind that many units can be related to many grades).
I tried creating a different intermediate table that contains (with the mouthful title list_grades_list_subjects_list_units):
ListUnit model
public function list_subjects()
{
return $this->belongsToMany('App\ListSubject', 'list_grades_list_subjects_list_units', 'list_subject_id', 'list_unit_');
}
I'm left scratching my head. Perhaps I have been looking at this for way too long, but I feel as though my head might explode soon!
Not sure if the solution exists in restructuring intermediate tables, reworking the model functions, or looking at the relationship through a different lens (Polymorphic?)? Hoping someone can help me see the light!
Please or to participate in this conversation.