我使用Rails 4.2.0和ActiveRecord。我有Case
型號,其中has_many :notes
。在rails中關聯關聯範圍的子查詢
我的主要目標是在一個查詢中獲取每個案例的最新備註。註釋字段應該是排序(ORDER BY notes.created_at
,例如),我可以通過這樣的SQL查詢實現這一目標:
SELECT cases.*, notes.* FROM cases
LEFT OUTER JOIN notes ON cases.id = notes.case_id AND notes.id = (
SELECT id FROM notes
WHERE notes.case_id = cases.id
ORDER BY notes.created_at DESC
LIMIT 1
)
ORDER BY notes.created_at DESC
我現在case.rb
代碼如下:
has_one :latest_note, -> do
where('id' => Note.where('"case_id" = "cases"."id"').order(created_at: :desc).limit(1))
end, inverse_of: :case, class_name: 'Note'
它工作正常,當eager_load
使用: Case.eager_load(:latest_note).order('notes.created_at DESC')
SELECT "cases"."id" AS t0_r0, "cases"."created_at" AS t0_r1, "cases"."updated_at" AS t0_r2, "notes"."id" AS t1_r0, "notes"."case_id" AS t1_r1, "notes"."created_at" AS t1_r2, "notes"."updated_at" AS t1_r3
FROM "cases" LEFT OUTER JOIN "notes"
ON "notes"."case_id" = "cases"."id"
AND "notes"."id" IN (
SELECT "notes"."id" FROM "notes"
WHERE ("case_id" = "cases"."id")
ORDER BY "notes"."created_at" DESC
LIMIT 1
) ORDER BY notes.created_at DESC
但引發錯誤SQLite3::SQLException: no such column: cases.id
沒有eager_load
: Case.first.latest_note
SELECT "notes".* FROM "notes"
WHERE "notes"."case_id" = ? AND "notes"."id" IN (
SELECT "notes"."id" FROM "notes"
WHERE ("case_id" = "cases"."id")
ORDER BY "notes"."created_at" DESC
LIMIT 1
) LIMIT 1
附:有沒有關聯範圍的解決方案?通過joins
的原始左連接不能與eager_load
一起使用。如果沒有eager_load
,它不會將數據庫中的值映射到對象 - 日期保持爲字符串,而不是DateTime
對象。
避免該警告「JOIN events on events.starts_on = users.birthday」},class_name:'Event'' – s2t2 2017-01-14 17:38:25