我正在尝试编写带有条件的嵌套联接查询。

我现在有的查询是:

Event.joins(:store => :retailer).where(store: {retailer: {id: 2}})

输出以下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
'

还有以下错误:
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
'

它告诉我没有列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

最佳答案

看起来您不需要此处的嵌套联接。尝试使用类似

Event.joins(:store).where(stores: {retailer_id: 2})

嵌套联接也应使用stores起作用
Event.joins(:store => :retailer).where(stores: {retailer: {id: 2}})

10-06 05:25