【发布时间】:2014-09-01 13:17:52
【问题描述】:
我有模型Post、Tag 和PostTag。一篇文章通过文章标签有许多标签。我想查找专门标记有多个标签的帖子。
has_many :post_tags
has_many :tags, through: :post_tags
例如,给定这个数据集:
posts table
--------------------
id | title |
--------------------
1 | Carb overload |
2 | Heart burn |
3 | Nice n Light |
tags table
-------------
id | name |
-------------
1 | tomato |
2 | potato |
3 | basil |
4 | rice |
post_tags table
-----------------------
id | post_id | tag_id |
-----------------------
1 | 1 | 1 |
2 | 1 | 2 |
3 | 2 | 1 |
4 | 2 | 3 |
5 | 3 | 1 |
我想查找带有tomato 和basil 标记的帖子。这应该只返回“Heart burn”帖子(id 2)。同样,如果我查询带有tomato 和potato 标记的帖子,它应该返回“碳水化合物超载”帖子(id 1)。
我尝试了以下方法:
Post.joins(:tags).where(tags: { name: ['basil', 'tomato'] })
SQL
SELECT "posts".* FROM "posts"
INNER JOIN "post_tags" ON "post_tags"."post_id" = "posts"."id"
INNER JOIN "tags" ON "tags"."id" = "post_tags"."tag_id"
WHERE "tags"."name" IN ('basil', 'tomato')
这会返回所有三个帖子,因为它们都共享标签番茄。我也试过这个:
Post.joins(:tags).where(tags: { name 'basil' }).where(tags: { name 'tomato' })
SQL
SELECT "posts".* FROM "posts"
INNER JOIN "post_tags" ON "post_tags"."post_id" = "posts"."id"
INNER JOIN "tags" ON "tags"."id" = "post_tags"."tag_id"
WHERE "tags"."name" = 'basil' AND "tags"."name" = 'tomato'
这不会返回任何记录。
如何查询带有多个标签的帖子?
【问题讨论】:
标签: ruby-on-rails postgresql activerecord