如何通过PostSearchModel搜索包含两个或更多特定标签的帖子?

时间:2018-05-02 19:00:26

标签: yii2 yii2-model

请帮助我理解,怎么做。

例如,我有3个标签:

  • A;
  • B;
  • 下进行。

和3个帖子

  • 帖子1标签:A B;
  • 帖子2标签:B C;
  • 发布3标签:A B C。

我只需搜索标签为A,B,C的帖子。在此示例中,只有Post 3包含这些标记。

1 个答案:

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