回答

收藏

有条件的Rails Nested加入Activerecord

技术问答 技术问答 345 人阅读 | 0 人回复 | 2023-09-14

我正在尝试编写带有条件的嵌套联接查询。
; z& E8 f0 b. K/ R我现在有的查询是:& X8 K  t- U. \0 Z+ n( t
Event.joins(:store => :retailer).where(store: {retailer: {id: 2}})
/ T) p/ ?8 `: d% Z输出以下SQL:
) N) T2 P9 d! J4 ^   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" = '---3 x. D$ P7 A' I& f  i
:id: 29 P1 f( Y3 D( J( {
'
' X7 z7 o6 }) \- \; H% \/ {0 c还有以下错误:
  J4 W0 ^) m, I. nSQLite3::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" = '---
# W9 b8 ?! T, {5 z; V% j  M4 [' w:id: 2
6 ~+ w( N8 A& u( C': D$ z% d& k8 u2 N9 [0 u# Y( \$ g& v( O+ v
它告诉我没有列store.retailer_id,但是,我可以运行以下查询,它将正常工作:4 v; v" k. ]6 F3 J9 D
Event.first.store.retailer_id
* W2 z; k) n, Y* {7 a  Event Load (0.2ms)  SELECT  "events".* FROM "events"   ORDER BY "events"."id" ASC LIMIT 12 A6 Q# Y, J3 S) Y! w
  Store Load (0.1ms)  SELECT  "stores".* FROM "stores"  WHERE "stores"."id" = ? LIMIT 1  [["id", 28958]]/ v( T- E6 V: G2 h4 ~
=> 41 ?% ?% [- @5 j9 F+ \" Z
                : H8 J9 `6 O4 n1 f* C  |* m
解决方案:! [/ V, n# G. Y" }: L
               
; V( p; A7 s: U4 Q9 m3 Z
( x% \; R: V3 ~* C# \3 G5 Y( `$ n. @, b& v3 ^8 K; S
                看起来您不需要在这里嵌套嵌套。尝试使用类似
+ W6 c. f0 P( m6 M, n* B5 iEvent.joins(:store).where(stores: {retailer_id: 2})
) ?& O6 b: P) A1 j4 f嵌套连接也可以使用 stores( S: r  n# O  @& q0 z
Event.joins(:store => :retailer).where(stores: {retailer: {id: 2}})
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则