假设您有一个posts表和一个tags表,它们通过一个post_tags表相关联。
posts有id/subject/body列
标签有id/name
post_tags有id/post_id/tag_id
在rails术语中,我有一个Post Model,它通过AssetTags有许多标签。
我正试图查询一个有2个特定标签的帖子。因此,如果有一个rails标签和一个mysql标签,我想要一个查询,返回一个帖子,只有这两个标签。
有意义吗?
任何方法来做到这与activerecord(我使用搜索逻辑)或mysql?
此SQL返回包含两个标记的帖子。
select
p.*
from
posts p
,asset_tags atg1
,asset_tags atg2
,tags t1
,tags t2
where
p.id = atg1.post_id
and t1.id = atg1.tag_id
and t1.tag = 'MySQL'
and p.id = atg2.post_id
and t2.id = atg2.tag_id
and t2.tag = 'Rails'
;
至于通过活动记录,另一种选择是查询每个标签,然后&生成的数组,以获得两者的交集。
给定这些模型:
def Post
has_many :asset_tags
has_many :tags, :through => :asset_tags
end
def AssetTag
has_one :post
has_one :tag
end
def Tag
has_many :asset_tags
has_many :posts, :through => :asset_tags
end
你可以这样做:
Post.joins(:asset_tags => :tag).where(
"tags.name in ('?', '?')", 'foo', 'bar' )
现在,这实际上对has_many :through
关联没有做任何事情——我不确定是否有一个更流畅的api提供使用它
对于mysql,当然可以获取数据
SELECT p.*
FROM posts p
JOIN post_tags pt
ON p.post_id = pt.post_id
WHERE pt.tag_id in (tagId1, tagId2)
我没有使用Rails的ActiveRecord,但我想这将是沿着
一行的东西 get('posts');
join('post_tags','post_id');
where_in('tag_id', array(tagId1, tagId2);
execute();
John Bachir的回答可以修改为…
Post.joins(:asset_tags => :tag)
.where("tags.name in ('?')", 'foo')
.where("tags.name in ('?')", 'bar')