Reputation: 61
For a school platform I would like to have list with all the students that are enrolled in a class with a certain schoolYear. In this list I would like to see the id, last_name, first_name and the class name of each student.
The Id + full name is no problem, but loading all the relationships and displaying the full class name with grade doesn't work.
my relationships are as following:
student -> hasMany -> Enrollments
-----------Enrollments -> belongsTo -> offering
--------------------------offering -> belongsTo -> schoolClasses
--------------------------offering -> belongsTo -> schoolyears
--------------------------------------schoolClass -> belongsTo -> grade
The class name consists out of the grade name + class name (e.g. Nursery 1 + A).
My EER is as following:
Currently I have this working:
By doing this in my controller:
$students = Student::with('offerings.schoolClasses.grades')->get();
return view('student.overview', ['students' =>$students]);
and this in my view:
@foreach($students as $student)
<tr>
<th scope="row">{{$student->id}}</th>
<td>{{$student->first_name}}</td>
<td>{{$student->last_name}}</td>
<td>{{$student->offerings}}</td>
</tr>
@endforeach
Could someone help me getting the final bits?
Upvotes: 0
Views: 63
Reputation: 61
I found out what was wrong, the definition of my relationships in my models didn't contain a foreign key to reference on.
I had to add explicit foreign keys when referencing the relationship:
public function schoolClass(){
return $this->belongsTo(SchoolClass::class,'school_class_id');
}
public function schoolyears(){
return $this->belongsTo(Schoolyear::class,'schoolyear_id');
}
The school_class_id
and schoolyear_id
where necessary to load everything correctly.
Upvotes: 0
Reputation: 1225
I think you can try like this:
$students = Student::with('offerings.schoolClasses.grades')
->with(array('offerings.schoolYears'=>function($query){
$query->where('start', '=', $somedate)
}))
->get();
and you can try this to show the grade:
{{$student->offerings->schoolClasses->grades->grade}}
Upvotes: 0