简体   繁体   English

具有嵌套关联和组的Rails查询(按关联对象)

[英]Rails Query with nested association and group ( by associated object)

Given this model relationships: 给定此模型关系:

orders.rb
belongs_to user

user.rb
belongs_to company

company.rb
has_many users

I wanted to count all orders made by each company, so I got this: 我想计算每个公司的所有订单,所以我得到了:

Order.joins(user: :company)
.group(['companies.name, companies.id])
.count

and the result is 结果是

["Company 1", 1] => 123 [“公司1”,1] => 123

BUT I don't know how to change this query to have 但是我不知道如何更改此查询

<Company id: 1,name: "Jim Beam"> => 5

instead of array of Company's attributes. 而不是公司属性的数组。

This can be made easier by adding another association to the model: 通过向模型添加另一个关联,可以使此过程更容易:

# company.rb
has_many :users
has_many :orders, through: :users

Then you can do this: 然后,您可以执行以下操作:

   companies = Company.
               joins(:orders).
               group("company.id").
               select("company.id, company.name, count(orders.id) as orders_count")

if you then say companies.first you will see something like this: 如果您接着说companies.first您将看到类似以下内容:

#<Company:0x005610fa35e678 id: 15 name: 'foo'>

it doesn't look like the orders_count is there. 它看起来好像不存在orders_count But it actually has been loaded already. 但实际上它已经被加载了。 You can get at it like this: 您可以这样实现:

companies.first.orders_count

You can also see it if you convert the company to a hash: 如果将公司转换为哈希,也可以看到它:

companies.first.attributes # => { id: 15, orders_count: 2, name: "foo" }

In Postgres at least, if you want to get more data in the attributes hash you have to individually specify each of the columns in the select string. 至少在Postgres中,如果要在属性哈希中获取更多数据,则必须分别指定select字符串中的每一列。 I'm not sure about other databases. 我不确定其他数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM