Skip to content

Eager loading relations inside a local scope #17328

@sebastiaanluca

Description

@sebastiaanluca
  • Laravel Version: 5.3.29
  • PHP Version: 7.1.0
  • Database Driver & Version: MySQL 14.14 Distrib 5.7.16

Description:

Loading model relations inside a local scope doesn't work. Related models don't get eager loaded, relation callbacks aren't even executed.

Are scopes limited in what they can do? Since it gets the query builder object, I supposed it had full access to model functions? I noticed $this inside the scope doesn't do much either as that model instance gets ditched after applying the scope query. That's ok, yet I expect the query to be applied to the results or instance that gets the results.

Steps To Reproduce:

A simple relation I want to load when the scope is added:

MyModel::withRandomRelation()->get();
public function someRelation() : HasMany
{
    return $this->hasMany(MyClass::class);
}

public function scopeWithRandomRelation($query) : Builder
{
    return $query->with('someRelation');
}

Callback is never executed:

public function scopeWithRandomRelation($query) : Builder
{
    return $query->with([
        'someRelation' => function ($query) {
            \Log::debug('Never called.');

            return $query;
        }
    ]);
}

Related

Perhaps related: #11793

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions