0
我想通過關係字段進行全局範圍過濾。Laravel:全球範圍與whereHas和多對多關係
// 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);
版本是BelongsToMany關係和版本()返回一個版本的對象。
不過,我記錄的查詢,並呈現出這樣的事:
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專家,所以我不真正瞭解如何在JOIN內部使用EXISTS子查詢。
但我看到如果我做下一個代碼的東西一切工作正常。但我需要過濾所有查詢,所以我認爲我需要一個全局範圍。
User::whereHas('versions', function($query) {
return $query->where('version_id', version()->id)
});
任何想法?
的錯誤嘗試的限制來改變'whereHas(「VERSION_ID」 <...>'簡單'在哪裏('VERSION_ID '<...>' –
Oups,對不起。原始代碼是'where'not'whereHas',我在發佈代碼時犯了一個錯誤。 – kanashin