Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to a member function addEagerConstraints() on null because of a conditional relationship

Tags:

php

laravel

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?

like image 916
Sherlock Avatar asked Sep 14 '25 03:09

Sherlock


1 Answers

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.

like image 108
OMR Avatar answered Sep 16 '25 17:09

OMR