【发布时间】:2014-04-03 14:03:39
【问题描述】:
由于我无法控制的原因,我需要在 MySQL 中手动编写 SQL 查询。
我的模型是:
class Survey < ActiveRecord::Base
has_many :buildings
has_many :floors, through: :buildings
has_many :workspaces, through: :floors
end
class Workspace < ActiveRecord::Base
belongs_to :floor
end
class Floor < ActiveRecord::Base
has_many :workspaces
end
我需要根据它有多少工作空间来订购我的调查。
在 Rails 代码中,我可以执行以下操作:@survey.workspaces.size,这将获得@survey 拥有的工作区数量。
鉴于此 SQL 查询:
SELECT `surveys`.*
FROM `surveys`
ORDER BY surveys.workspaces.size asc
LIMIT 10
OFFSET 0
如何手动编写根据工作空间数量排序的查询?
【问题讨论】:
-
我会在这里使用命名范围...
-
我也会,但由于设计限制,我确实需要手工制作此查询。
标签: mysql sql ruby-on-rails activerecord