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
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:
#<Company:0x005610fa35e678 id: 15 name: 'foo'>
it doesn't look like the orders_count
is there. 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. I'm not sure about other databases.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.