yii2 - 如何通过 PostSearchModel 搜索具有两个或多个特定标签的帖子?
问题描述
请帮助我理解,如何做到这一点。
例如,我有 3 个标签:
- 一个;
- 乙;
- C。
还有3个帖子
- 发布带有标签的 1:AB;
- 发布带有标签的 2:BC;
- 发布带有标签的 3:AB C。
我只需要搜索带有标签 A、B、C 的帖子。在这个例子中,只有 Post 3 包含这些标签。
解决方案
如果您想查找具有所有三个标签的帖子,您需要使用三重连接构建查询 - 每个标签一个连接。假设您将标签关系定义为:
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();
推荐阅读
- php - 此集合实例上不存在属性 [img_pers]
- php - finfo_file(C:\xampp\tmp\phpC546.tmp):打开流失败:没有这样的文件或目录
- java - 是否有支持 2 个键的 Java Map 实现?
- java - 如何使用对象映射器反序列化Java中的嵌套对象
- wpf - WPF 如何在不覆盖派生样式的情况下将样式应用于自定义控件项
- nsis - 如何根据条件强制 NSIS 部分
- lazarus - Lazarus DBLookupCombobox 无法将 null 转换为 int64 以进行数据提交
- amazon-web-services - 是否有可能制定“无操作”IAM 政策?
- graph - 在 gremlin 查询中显示级别
- c++ - 非类类型表达式的静态与动态类型之间的区别