Framework: Eloquent Model global scope not working properly with belongsToMany relationship

Created on 20 Sep 2017  路  2Comments  路  Source: laravel/framework

Steps To Reproduce:

  1. I have three tables: posts, terms, relations;
  2. Assume term model has a global scope:
   protected static function boot()
    {
     parent::boot();
        static::addGlobalScope('category', function (Builder $builder) {
            $builder->where('type', 'category');
        });
    }
  1. And post model related with term model through relations table like this:
    public function terms()
    {
        return $this->belongsToMany(
            'App\Term', 'relations',
            'post_id', 'term_id'
        );
    }
  1. When I query post->terms(), result sql error:
    Integrity constraint violation: 1052 Column 'type' in where clause is ambiguous

  2. After testing a while, I found I need to modify step 2 to make it work properly:
    $builder->where('type', 'category'); => $builder->where('terms.type', 'category');

  3. As it is not documented, I decided to submit it here, while I'm not sure it should be considered an issue or not.

All 2 comments

Yes your global scope won't work in this situation when multiple tables has the same field name in your where clause, I suggest that you don't use a global scope in this case and adjust your query as per needed.

You could do that

 protected static function boot()
    {
       parent::boot();
       $table = (new static )->getTable();

        static::addGlobalScope('category', function (Builder $builder) use($table) {
            $builder->where("{$table}.type", 'category');
        });
    }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

CupOfTea696 picture CupOfTea696  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments

JamborJan picture JamborJan  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments

iivanov2 picture iivanov2  路  3Comments