protected static function boot()
{
parent::boot();
static::addGlobalScope('category', function (Builder $builder) {
$builder->where('type', 'category');
});
}
public function terms()
{
return $this->belongsToMany(
'App\Term', 'relations',
'post_id', 'term_id'
);
}
When I query post->terms(), result sql error:
Integrity constraint violation: 1052 Column 'type' in where clause is ambiguous
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');
As it is not documented, I decided to submit it here, while I'm not sure it should be considered an issue or not.
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');
});
}