Reputation: 134
I'm putting together a simple report card system in Laravel just as a learning tool. At present I have a Pupil
table, a Subject
table, and a Pupil_Subject
pivot table consisting of id, pupil_id, subject_id,
and grade
columns.
I have the Pupil and Subject model relationships both set to belongsToMany
. However, if I run, for example, $pupil = App\Pupil::find(1)->subjects
in Tinker, I get the following output:
Illuminate\Database\Eloquent\Collection {#729
all: [
App\Subject {#726
id: 1,
subjectname: "English",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {#731
pupil_id: 1,
subject_id: 1,
},
},
App\Subject {#728
id: 2,
subjectname: "Maths",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {#730
pupil_id: 1,
subject_id: 2,
},
},
],
}
With no pupil information for pupil(1), and no sign of the grade column in subjects
. What am I doing wrong?
Upvotes: 1
Views: 54
Reputation: 163898
If you need to get both Pupil
and Subject
objects, use eager loading:
$pupil = App\Pupil::with('subjects')->find(1);
Upvotes: 2