[英]How do you do this in mysql or rails
Say you have a posts table and a tags table, and both are related by a post_tags table. 假设您有一个posts表和一个tag表,并且两者都由post_tags表关联。
so 所以
posts has id/subject/body columns 帖子具有id / subject / body列
tags has id/name 标签具有ID /名称
post_tags has id/post_id/tag_id post_tags具有id / post_id / tag_id
in rails terminology, I have a Post Model that has many Tags through AssetTags. 用rails术语来说,我有一个Post模型,该模型通过AssetTags包含许多标签。
I'm trying to query for a post that has 2 specific tags. 我正在尝试查询具有2个特定标签的帖子。 so if there is a rails tag and a mysql tag, I want a query that returns a post that only has those two tags. 因此,如果有一个rails标记和一个mysql标记,我想要一个查询,该查询返回仅包含这两个标记的帖子。
make sense? 说得通?
Any way to do this with activerecord (I'm using search logic) or mysql? 有什么办法用activerecord(我正在使用搜索逻辑)或mysql做到这一点?
This SQL returns the posts that contain both tags. 此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'
;
As for doing it via Active record, an alternative would be to query for each of the tags and then & the resulting arrays to get the intersection of the two. 至于通过Active Record进行操作,另一种方法是先查询每个标签,然后再查询结果数组以获取两者的交集。
For mysql, sure, you can get the data 对于mysql,当然可以获取数据
SELECT p.*
FROM posts p
JOIN post_tags pt
ON p.post_id = pt.post_id
WHERE pt.tag_id in (tagId1, tagId2)
I have not used Rails ActiveRecord but I imagine it would be something along the lines of 我没有使用过Rails ActiveRecord,但我想这可能与
get('posts');
join('post_tags','post_id');
where_in('tag_id', array(tagId1, tagId2);
execute();
Given these models: 鉴于这些模型:
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
You can do this: 你可以这样做:
Post.joins(:asset_tags => :tag).where(
"tags.name in ('?', '?')", 'foo', 'bar' )
Now, this actually doesn't do anything with the has_many :through
association -- I'm not sure if there's an even slicker api provided that utilizes that. 现在,这实际上对has_many :through
关联没有任何作用-我不确定是否提供了什锦的api来利用它。
John Bachir's answer can be modified to... 约翰·巴希尔(John Bachir)的答案可以修改为...
Post.joins(:asset_tags => :tag)
.where("tags.name in ('?')", 'foo')
.where("tags.name in ('?')", 'bar')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.