1

我有 3 个模型:

class City < ActiveRecord::Base
  has_many :buildings
end
class Company < ActiveRecord::Base
  has_many :buildings
end
class Building < ActiveRecord::Base
  belongs_to :city
  belongs_to :company
end

我需要展示每个城市的建筑物,但按他们的公司排序如下:

city1
  company1
    building1
    building2
  company2
    building3
city2
  company1
    building5
    building6
    building4
  company2
    building7
    building8

我不知道如何进行查询,或者如何正确使用 rabl 来生成这个输出结构

编辑:

这是我暂时想到的:

city_controlles.rb:

def index
  @cities = City.all
  @companies = Company.includes(:buildings)
end

index.json.rabl:

collection @cities
attributes :id, :name
node :companies do |city|
  @companies.map do |company|
    { id: company.id, name: company.name, buildings:
     company.buildings.map do |building|
       if building.city_id == city.id
         { id: building.id, name: building.name }
       end
     end.compact
   }
  end
end
4

1 回答 1

-1

有很多方法可以做到这一点,具体取决于应该如何使用 rezult。

第一种方式:

SELECT 
    cities.name, companies.name, buildings.name
FROM
    cities
LEFT JOIN
   companies ON companies.city_id = city.id
LEFT JOIN 
    buildings ON buildings.city_id = city.id
ORDER BY
    cities.name, companies.name, buildings.name

Rezult 应该是这样的:

city1 | company1 | building1
city1 | company1 | building2
city1 | company2 | building3
city2 | company1 | building4
city2 | company1 | building5
city2 | company1 | building6
city2 | company2 | building7
city2 | company2 | building7

你可以用这张桌子做任何你想做的事。

第二种方式(使用聚合函数获取城市和公司的建筑物列表):

SELECT 
    cities.name, companies.name, GROUP_CONCAT(buildings.name)
FROM
    cities
LEFT JOIN
   companies ON companies.city_id = city.id
LEFT JOIN 
    buildings ON buildings.city_id = city.id
ORDER BY
    cities.name, companies.name
GROUP BY
    cities.name, companies.name

这样Rezult应该是这样的:

city1 | company1 | building1, building2
city1 | company2 | building3
city2 | company1 | building4, building5, building6
city2 | company2 | building7, building8

注意 聚合函数的名称(GROUP_CONCAT - 对于 MySQL)在 DBMS 中不同。例如,在 firebird 中,它是“LIST”

于 2013-05-16T23:21:50.557 回答