SQL Rails Nested 有条件地加入 Activerecord
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25111426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails Nested Joins Activerecord with conditions
提问by stytown
I'm trying to write a nested joins query with a condition.
我正在尝试编写一个带有条件的嵌套连接查询。
The query I have right now is:
我现在的查询是:
Event.joins(:store => :retailer).where(store: {retailer: {id: 2}})
Which outputs the following SQL:
它输出以下 SQL:
SELECT "events".* FROM "events" INNER JOIN "stores" ON "stores"."id" = "events"."store_id" INNER JOIN "retailers" ON "retailers"."id" = "stores"."retailer_id" WHERE "store"."retailer_id" = '---
:id: 2
'
And also the following error:
还有以下错误:
SQLite3::SQLException: no such column: store.retailer_id: SELECT "events".* FROM "events" INNER JOIN "stores" ON "stores"."id" = "events"."store_id" INNER JOIN "retailers" ON "retailers"."id" = "stores"."retailer_id" WHERE "store"."retailer_id" = '---
:id: 2
'
It's telling me there is no column store.retailer_id, however, I can run the following query and it will work just fine:
它告诉我没有列 store.retailer_id,但是,我可以运行以下查询,它会正常工作:
Event.first.store.retailer_id
Event Load (0.2ms) SELECT "events".* FROM "events" ORDER BY "events"."id" ASC LIMIT 1
Store Load (0.1ms) SELECT "stores".* FROM "stores" WHERE "stores"."id" = ? LIMIT 1 [["id", 28958]]
=> 4
回答by dimuch
Looks like you don't need nested joins here. Try to use something like
看起来您在这里不需要嵌套连接。尝试使用类似的东西
Event.joins(:store).where(stores: {retailer_id: 2})
Nested join should also work using stores
嵌套连接也应该使用 stores
Event.joins(:store => :retailer).where(stores: {retailer: {id: 2}})
回答by Rio Dermawan
There is the simplest way instead of using curly brackets :
有最简单的方法而不是使用大括号:
Event.joins(:store => :retailer).where('stores.retailer_id => ?', 2)
回答by Panos Malliakoudis
You should be able to access the retailers id
with the following syntax:
您应该能够使用retailers id
以下语法访问:
Event.joins(:store => :retailer).where('retailers.id' => 2)
ps. tested on Rails 5
附:在 Rails 5 上测试