简体   繁体   English

Rails使用连接关联提取值

[英]Rails extract values with join associations

I have a rails join table between 2 models superhero and superpower . 我有两个模型superherosuperpower之间的铁路连接表。 Now I have 3 different superpower id and I want all the superheroes which have all the selected superpowers 现在我有3个不同的superpower id ,我希望所有superheroes都拥有所有选定的superpowers

To do that I'm trying to do the following: 为此,我正在尝试执行以下操作:

matches = Superhero.all
matches = matches.joins(:superpowers).where('superpowers.id = ?', 17).where('superpowers.id = ?', 12).where('superpowers.id = ?', 6)

But this gives me an empty object even though I have superheroes which have all the given superpowers in my join table 但是这给了我一个空的对象,即使我有superheroes在我的连接表中拥有所有给定的superpowers

The query generated from the above is: 从上面生成的查询是:

SELECT "superheroes".* FROM "superheroes" INNER JOIN "superheroes_superpowers" ON "superheroes_superpowers"."superhero_id" = "superheroes"."id" INNER JOIN "superpowers" ON "superpowers"."id" = "superheroes_superpowers"."superpower_id" WHERE (superpowers.id = 17) AND (superpowers.id = 17) AND (superpowers.id = 12) AND (superpowers.id = 6)

So weirdly it tries to check for the superpower with id 17 twice (but it shouldn't affect the result I think) and the rest of the query seems to be correct. 所以很奇怪它试图检查id为17的superpower两次(但它不应该影响我认为的结果),其余的查询似乎是正确的。

try using an in clause 尝试使用in子句

superpowers_ids = [17,12,6]
matches = Superhero.all
matches = matches.joins(:superpowers).where('superpowers.id in (?)', superpowers_ids)
Superhero.joins(:superpowers).where(superpowers:  { id: [17,12,6] } )

This gives the following SQL query (formatted for readibility): 这给出了以下SQL查询(格式化为可读性):

SELECT "superheros".* 
FROM "superheros" 
INNER JOIN "superhero_superpowers" ON "superhero_superpowers"."superhero_id" = "superheros"."id" 
INNER JOIN "superpowers" ON "superpowers"."id" = "superhero_superpowers"."superpower_id" 
WHERE "superpowers"."id" IN (17, 12, 6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM