skip to Main Content

I have a model, Project, that I am eager loading relations in the Http/Controller.

The problem is that the withDefault closure on the belongsTo Relation in the model always fires, regardless of if there is an actual relation to eager load, resulting in many pointless queries and strange side effects.

This doesn’t seem like it should be expected behaviour – is there any way to stop it calling withDefault() unless it actually needs to?

To clarify:

return $project->loadMissing('address');

From the model:

    public function address(): BelongsTo
    {
        return $this
            ->belongsTo(Address::class, 'address_id')
            ->withDefault(function() {
                // This will always trigger
            });
    }

withDefault triggers always, regardless of the state of the actual relation.

2

Answers


  1. Are you sure, when say ‘eager’ you executed your query using ‘with’ function?

    Example:

    $query = $this->model->newQuery();
    $query->with('cargos');
    $query->with('tasks');
    ...
    ...
    /** @var Order $order */
    $order = $query->get()->first();
    
    Login or Signup to reply.
  2. In your Project model, you can define a boolean property to track whether the relationship was eager loaded. Then, you can override the load and loadMissing methods in your model to set this flag when loading relationships.

    protected $relationLoaded = false;
    
    public function load($relations)
    {
        parent::load($relations);
        $this->relationLoaded = true;
        return $this;
    }
    
    public function loadMissing($relations)
    {
        parent::loadMissing($relations);
        $this->relationLoaded = true;
        return $this;
    }
    

    Then you can check in your closure if relation was eager loaded or not.

    public function address(): BelongsTo
    {
        return $this
            ->belongsTo(Address::class, 'address_id')
            ->withDefault(function () {
                if (!$this->relationLoaded) {
                    // This will only trigger when the relationship is not eager loaded
                }
            });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search