有条件的Rails Nested加入Activerecord
技术问答
304 人阅读
|
0 人回复
|
2023-09-14
|
我正在尝试编写带有条件的嵌套联接查询。 ?" i5 M; p' m) t4 d0 e0 l
我现在有的查询是:
* s5 O. J% z) ]- c5 s4 N4 ^Event.joins(:store => :retailer).where(store: {retailer: {id: 2}}): r9 t' l( B1 s6 u+ x: M7 }
输出以下SQL:
* u$ n2 J x( k" J8 i 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" = '---( W3 G/ w$ S4 P/ C+ {
:id: 2
) R" E/ t" S- a. }; @1 ?1 V'
7 q8 B/ J6 E0 ?; l# x还有以下错误:9 ?, p1 f6 l1 H0 X
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" = '---
( I' _# q2 J" V$ B* D:id: 21 Y% G/ T4 g+ _) }: e
'
5 v8 m" U. Q* C3 h% R4 ~它告诉我没有列store.retailer_id,但是,我可以运行以下查询,它将正常工作:
( U/ P3 w5 S+ g: G: tEvent.first.store.retailer_id x/ s- |- \; [0 u2 `
Event Load (0.2ms) SELECT "events".* FROM "events" ORDER BY "events"."id" ASC LIMIT 16 M% M1 p( A* p' M6 I1 d" b1 n
Store Load (0.1ms) SELECT "stores".* FROM "stores" WHERE "stores"."id" = ? LIMIT 1 [["id", 28958]]
' d$ d# V8 p/ z3 E i7 \=> 4
m& G( H- Z$ z2 g+ n
* N/ j' ]+ m6 U解决方案:
/ u+ F* L2 ?2 s, U' z5 J7 p
6 b$ h- c! R2 A5 L
* `( p% T3 G# Y# r
$ ~" {, j6 T& o& z T8 C+ \- G( q' A 看起来您不需要在这里嵌套嵌套。尝试使用类似
, e- ^$ t5 f/ _2 h8 D5 DEvent.joins(:store).where(stores: {retailer_id: 2})+ L) r( S4 r6 ~! I9 g2 X$ T- t
嵌套连接也可以使用 stores
3 }4 m& _* C m& _% T" @Event.joins(:store => :retailer).where(stores: {retailer: {id: 2}}) |
|
|
|
|
|