Laravel5.5 对模型进行全局作用域限制后使用 hasManyThrough 模型关系时,若关联表作用域限制字段相同会报 MySQL 错误
版本 :laravel 5.5.44 /mysql 5.7
错误:mysql联表时存在相同字段未指定表名
场景:存在三个Model,分别为Script Channel News 三个模型均在boot方法中设置了全局作用域限制site_id为用户所属site_id
$site_id = $user->site_id ?? 0;
static::addGlobalScope('site_id', function(Builder $builder) use ($site_id) {
$builder->where('site_id', $site_id);
});
在Script中存在hasManyThrough模型关系
public function channel(){
return $this->hasManyThrough('App\Models\Channel', 'App\Models\News', $this->foreignKeyName, 'id', 'id', 'channel_id');
}
调用$script->channel时报错如下:
"SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'site_id' in where clause is ambiguous (SQL: select
channels
.*,news
.script_id
fromchannels
inner joinnews
onnews
.channel_id
=channels
.id
wherenews
.deleted_at
is null andnews
.script_id
= 182 andchannels
.deleted_at
is null andsite_id
= 262)"
查看日志发现好像所有的全局作用域在生成SQL语句时都不限定表名的,请问该如何解决?这是否属于laravel的bug?
(new static)->getTable()