Skip to content

MorphTo when getResultsByType not reset applied Global Scopes since 5.2.34 #13826

Closed
@xian13

Description

@xian13

@phroggyy your clone $this->query in the #13724 and some update in the #13737 still has some bugs related with global scopes.

In my project we create a global scopes in Model X and Model X has a MorphTo relation inside it :

class X extends Model
{

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('x', function($builder) {
            $builder->where('x', true);
        });
    }

    public function morph()
    {
         return $this->morphTo();
    }
}

When we load the relation 'morph' what happens is that our Global Scope 'x' is included because it clone the query and still has the previous global scopes inside it.

protected function getResultsByType($type)
{
    $instance = $this->createModelByType($type);
    $key = $instance->getTable().'.'.$instance->getKeyName();
    $query = clone $this->query;
    $query->setEagerLoads($this->getEagerLoadsForInstance($instance));
    $query->setModel($instance);
    return $query->whereIn($key, $this->gatherKeysByType($type)->all())->get();
}

the $query still has the previous scopes set in model 'X'.
What is the purpose of cloning the query?
The problem isn't occurred in the 5.3.3 because it will use newQuery from the $instance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions