[英]converting sql with multilevel joins to rails activerecord expression
'SELECT "complaints".* FROM "complaints" INNER JOIN "machines" ON "machines"."id" = "complaints"."machine_id" INNER JOIN "mclns" ON "machines"."mcln_id" = "mclns"."id" ORDER BY "mclns"."response_time" ASC'
I need the above sql to be converted to Active record statement 我需要将上面的sql转换为活动记录语句
complaint
model does not know about mcln
it has to go through machine
complaint
模型不知道mcln
它必须通过machine
Complaint.joins(:machine=>:mcln)
gives Complaint.joins(:machine=>:mcln)
给出
SELECT "complaints".* FROM "complaints" INNER JOIN "machines" ON "machines"."id" = "complaints"."machine_id" INNER JOIN "mclns" ON "mclns"."machine_id" = "machines"."id"
but I need 但是我需要
SELECT "complaints".* FROM "complaints" INNER JOIN "machines" ON "machines"."id" = "complaints"."machine_id" INNER JOIN "mclns" ON "machines"."mcln_id" = "mclns"."id"
Update: 更新:
A machine can have a mcln and also many machines can have same mcln. 一台机器可以具有mcln,许多机器也可以具有相同的mcln。
I have implemented it by using 我已经通过使用实现了
has_one :mcln
on Machine
model and belongs_to :machine
on Mcln
在Machine
模型上具有has_one :mcln
,在Mcln
上具有Mcln
belongs_to :machine
And I'm not sure if thats correct implementation. 而且我不确定那是否是正确的实现。
try out this : 试试这个:
SELECT complaints.*,machines.*,mclns.* FROM `complaints`
INNER JOIN `machines`
ON ( machines.id = complaints.machine_id )
INNER JOIN `mclns`
( ON machines.mcln_id = mclns.id )
Your association is incorrect. 您的关联不正确。 If many machines can have the same mcln then the machines table should have a mcln_id column and your classes should look like 如果许多机器可以具有相同的mcln,那么machines表应该具有mcln_id列,并且您的类应如下所示
class Machine < AR::Base
belongs_to :mcln
end
class Mcln < AR::Base
has_many :machines
end
Then Complaint.joins(:machine => :mcln)
should generate the SQL you want 然后Complaint.joins(:machine => :mcln)
应该生成您想要的SQL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.