【发布时间】:2016-05-12 17:16:56
【问题描述】:
我想通过关系的字段进行全局范围过滤。
// The *apply* method of VersionScope file is:
$builder->whereHas('versions', function ($query) {
return $query->where('version_id', '=', version()->id);
});
// Users'boot method has this line after parent:boot();
static::addGlobalScope(new VersionScope);
versions 是 BelongsToMany 关系,version() 返回一个 Version 对象。
但是我记录了查询并显示如下内容:
select *
from users
where users.id = ?
where exists (
select *
from versions
inner join user_version on user_version.version_id = versions.id
where user_version.user_id = users.id
and user_version.version_id = ?
)
如果 EXISTS 子查询是第一个关系,则它可以正常工作,例如:
id|user_id|version_id
1 |1 |1
2 |1 |2
如果 version_id = 1,查询工作正常,但如果 version_id = 2,我得到空结果。我不是 MySQL 专家,所以我不太了解 EXISTS 子查询如何工作,其中包含 JOIN。
但我看看我是否执行下一个代码之类的操作一切正常。但我需要过滤所有查询,所以我认为我需要一个全局范围。
User::whereHas('versions', function($query) {
return $query->where('version_id', version()->id)
});
有什么想法吗?
【问题讨论】:
-
尝试将
whereHas('version_id'<...>改为简单的where('version_id'<...> -
哎呀,对不起。原始代码是“where”而不是“whereHas”,我在发布代码时犯了一个错误。更新中