首页 > 解决方案 > 如何通过 PostSearchModel 搜索具有两个或多个特定标签的帖子?

问题描述

请帮助我理解,如何做到这一点。

例如,我有 3 个标签:

还有3个帖子

我只需要搜索带有标签 A、B、C 的帖子。在这个例子中,只有 Post 3 包含这些标签。

标签: yii2yii2-model

解决方案


如果您想查找具有所有三个标签的帖子,您需要使用三重连接构建查询 - 每个标签一个连接。假设您将标签关系定义为:

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();

推荐阅读