I have to deal with a Laravel 7 application that has a sub-optimal database design, leading to the error mentioned in the title.
The database looks like this:
mains
- id
- sub_type
subs_a
- id
- main_id
subs_b
- id
- main_id
Then I have a class Main with method sub:
public function sub()
{
switch($this->sub_type) {
case 'a':
return $this->hasOne('SubTypeA');
break;
case 'b':
return $this->hasOne('SubTypeB');
break;
default:
return null;
}
}
This code works in 99% of all cases, but Laravel sometimes loads an empty instance of Main and then tries to load the relations. That doesn't work, because the default of method sub is null.
Restructuring the database is on the to-do list, but that isn't of any help right now.
What option do I have to stop Laravel from trying to load the sub relation on an empty object?
i know it's some kind of expected, but have tried to return an empty relation?
public function sub()
{
switch($this->sub_type) {
case 'a':
return $this->hasOne('SubTypeA');
break;
case 'b':
return $this->hasOne('SubTypeB');
break;
default:
return $this->newQuery(); // or newQueryWithoutScopes()
}
}
thank to this answer. it should prevent the error of addEagerConstraints() on null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With