問(wèn)題描述
我正在嘗試向我的項(xiàng)目添加兩個(gè)不同的搜索變體.有一個(gè)模型用戶(hù)"和一個(gè)模型標(biāo)簽".一個(gè)用戶(hù)有很多標(biāo)簽.現(xiàn)在我希望能夠搜索具有特定標(biāo)簽的用戶(hù).我想顯示所有具有任何指定標(biāo)簽的用戶(hù).我是這樣工作的:
I am trying to add to two different search variations to my project. There is a model "User" and a model "Tag". A User has many Tags. Now I want to be able to search the Users with specific Tags. Either I want to show all Users that has any of the specified tags. I got this working this way:
$query = $this->Users->find();
$query->matching('Tags', function ($q) {
return $q->where(['Tags.name' => 'Tag1'])
->orWhere(['Tags.name' => 'Tag2']);
});
但現(xiàn)在我想找到同時(shí)擁有兩個(gè)標(biāo)簽的所有用戶(hù).我試過(guò) ->andWhere
而不是 ->orWhere
,但結(jié)果總是空的.
But now I want to find all Users that have both Tags at the same time.
I tried ->andWhere
instead of ->orWhere
, but the result is always empty.
如何找到包含多個(gè)標(biāo)簽的用戶(hù)?
How can I find Users that contain multiple Tags?
謝謝
推薦答案
有幾種方法可以實(shí)現(xiàn)這一點(diǎn),一種是將結(jié)果分組并使用 HAVING
來(lái)比較不同的計(jì)數(shù)標(biāo)簽
There are a few ways to achieve this, one would be to group the results and use HAVING
to compare the count of the distinct tags
$query = $this->Users
->find()
->matching('Tags', function ($query) {
return $query->where(['Tags.name IN' => ['Tag1', 'Tag2']]);
})
->group('Users.id')
->having([
$this->Users->query()->newExpr('COUNT(DISTINCT Tags.name) = 2')
]);
這將僅選擇具有兩個(gè)不同標(biāo)簽的用戶(hù),它們只能是 Tag1
和 Tag2
,因?yàn)樗鼈兪俏ㄒ槐患尤氲挠脩?hù).以防萬(wàn)一name
列是唯一的,您可以改為依賴(lài)主鍵.
This will select only those users that have two distinct tags, which can only be Tag1
and Tag2
since these are the only ones that are being joined in. In case the name
column is unique, you may count on the primary key instead.
IN
順便說(shuō)一句.本質(zhì)上與您的 OR
條件相同(數(shù)據(jù)庫(kù)系統(tǒng)會(huì)相應(yīng)地將 IN
擴(kuò)展為 OR
條件).
The IN
btw. is essentially the same as your OR
conditions (the database system will expand IN
to OR
conditions accordingly).
這篇關(guān)于如何匹配與一組特定的其他記錄相關(guān)聯(lián)的記錄?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!