Something pretty strange is happening in my relationships in Laravel. Especially with the whereHas
.
I'm trying to get all the Lecture
that belongs to a certain School
. I have the following structure:
Lecture -> Course -> School
.
I have the following relationships defined:
Lecture.php
public function course(){
return $this->belongsTo(Course::class, 'course_id');
}
Course.php
public function school(){
return $this->belongsTo(School::class, 'school_id');
}
Applying the relationship:
$lectures = $lectures->whereHas('course.school', function ($q) use ($request){
$q->where('id', $request->get('school_id'));
});
Error
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'calendarzito.school' doesn't exist (SQL: select count(*) as aggregate from `school` where `id` = 2)
Note the s
missing at school
.
What have I tried:
Logically first I thought the Model School had a bad name and tried to define manually the name of the table with protected $table = 'schools'
but still the table name is being changed to school
and not schools
.
I tried using Tinker to check if the relationship is correct and it was indeed Lecture::first()->course->school
and it returns the right school.
Anyone has faced a problem like this before?
Thank you for everyone for the help but the problem ended up being a validation error and not actually the relationship itself.
Validator::validate($request->all(), [
'school_id' => 'exists:school,id'
])
Note the missing s
at school.
I guess its time for more coffee.