请帮助我理解,怎么做。
例如,我有3个标签:
和3个帖子
我只需搜索标签为A,B,C的帖子。在此示例中,只有Post 3包含这些标记。
答案 0 :(得分:0)
如果要查找包含所有三个标记的帖子,则需要使用三重连接构建查询 - 每个标记一个连接。假设您将标记关系定义为:
public function getTags() {
return $this->hasMany(Tag::class, ['id' => 'tag_id'])
->viaTable('{{%posts_tags}}', ['post_id' => 'id']);
}
你应该能够得到你想要的东西:
$posts = Post::find()
->innerJoinWith('tags as tags1', false)
->andWhere(['tags1.name' => 'A'])
->innerJoinWith('tags as tags2', false)
->andWhere(['tags2.name' => 'B'])
->innerJoinWith('tags as tags3', false)
->andWhere(['tags3.name' => 'C'])
->all();
或者,您可以将COUNT()
与GROUP BY
一起使用并计算匹配代码的数量,但如果您允许多次为一个帖子分配一个代码,这将是不可靠的。
$posts = Post::find()
->innerJoinWith('tags', false)
->andWhere(['tags.name' => ['A', 'B', 'C']])
->groupBy('posts.id')
->having('COUNT(*) >= 3')
->all();