考虑以下关联:
class Pool < ActiveRecord::Base
has_and_belongs_to_many :participations
end
class Participation < ActiveRecord::Base
has_and_belongs_to_many :pools
end
我想获得每个池中的参与次数(即使没有参与)。
这是我所期待的(id是池ID):
+----+----------------------------+
| id | count('participations.id') |
+----+----------------------------+
| 1 | 1 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
+----+----------------------------+
这就是我得到的:
+----+----------------------------+
| id | count('participations.id') |
+----+----------------------------+
| 1 | 3 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 6 | 1 |
| 7 | 1 |
| 8 | 1 |
+----+----------------------------+
要获得此结果,我使用group by和count进行左连接:
Pool.joins('LEFT JOIN participations_pools ON participations_pools.pool_id = pools.id LEFT JOIN参与ON participations.id = participations_pools.participation_id')。选择(“pools.id, 计数( 'participations.id')“)。组( 'pools.id')
我不知道如何获得好结果以及为什么会得到这个结果?
编辑:
我的回答是我的问题:
Pool.joins('LEFT JOIN participations_pools ON participations_pools.pool_id = pools.id LEFT JOIN参与ON participations.id = participations_pools.participation_id')。选择(“pools.id, 计数(participations.id)“)。组( 'pools.id')
围绕伯爵的报价引起了我的麻烦
答案 0 :(得分:1)
如果您不想担心,请仅使用ActiveRecord方法编写查询:
Pool.joins('LEFT JOIN participations_pools ON participations_pools.pool_id = pools.id')
.joins('LEFT JOIN participations ON participations.id = participations_pools.participation_id')
.group('pools.id').count('participations.id')
结果将是一个散列,其中pools.id
为关键字,count('participations.id')
为从数据库中提取的每一行的值。
count方法的更多信息:http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-count
If count is used with group, it returns a Hash whose keys represent the aggregated column, and the values are the respective amounts: