Pregunta

Currently in a model I do the following to automatically eager load all relationships:

public static $eagerLoad = ['country', 'product', 'membership.package'];

public function newQuery($excludeDeleted = true)
{
    $query = parent::newQuery(true);
    return $query->with(static::$eagerLoad);
}

How could I transport this to the BaseModel?

When I try it returns eloquent call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object

Update:

In my BaseModel I have like this:

public function newQuery($excludeDeleted = true)
{
    if(property_exists(get_class($this), 'eagerLoad'))
    {                       
        $query = parent::newQuery(true);
        return $query->with($this::$eagerLoad);
    }
}

It returns Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsTo::__construct() must be an instance of Illuminate\Database\Eloquent\Builder, null given, called in C:\xampp\htdocs\firebolt\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 713 and defined

If I leave empty or return false, it throws call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object

¿Fue útil?

Solución

You don't need to use that (the way you are doing it now for eager loading automatically) because all you need to do is only add a protected $with property in your model for example:

protected $with = ['country', 'product', 'membership.package'];

Now your model will automatically eager load the related model provided in $with. So if you do something like this:

$model = Model::find(1);

All the related models will be also eager loaded with this $model object.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top