[英]How do you do this in mysql or rails
假設您有一個posts表和一個tag表,並且兩者都由post_tags表關聯。
所以
帖子具有id / subject / body列
標簽具有ID /名稱
post_tags具有id / post_id / tag_id
用rails術語來說,我有一個Post模型,該模型通過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'
;
至於通過Active Record進行操作,另一種方法是先查詢每個標簽,然后再查詢結果數組以獲取兩者的交集。
對於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();
鑒於這些模型:
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來利用它。
約翰·巴希爾(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.