2017-06-14 77 views
0

是否可以连接两个表并计算两者的关系数?理想的输出是 [name, recommendation_count, review_count]Rails has_many多次连接记录数

class PatientProfile 
    has_many :reviews 
    has_many :recommendations 

# this works 
PatientProfile.joins(:reviews).group(:id).pluck(:name, 'count(reviews.id)') 

# this does not work 
PatientProfile.joins(:recommendations, :reviews).group(:id).pluck(:name, 'count(recommendations.id)', 'count(reviews.id)') 

第二个例子为列

+0

你能提供有关您的模型/关系的细节? – archana

+0

@archana增加了更多关于模型的信息 – user2954587

+0

你的'has_many:through'关系在哪里? – archana

回答

1

这应该返回'count(recommendations.id)'值:

PatientProfile 
    .joins(:recommendations, :reviews) 
    .group(:id) 
    .pluck(:name, 
     'count(distinct recommendations.id)', 
     'count(distinct reviews.id)') 

我强烈建议开始学习SQL。 ActiveRecord不是魔棒,而是构建SQL查询的工具。而且,ActiveRecord有它自己的限制。因此,在应用程序中使用RDBMS时,SQL是基础。

此外,阅读有关counter_cachethere将是有帮助的。它将简化和加快任何count(...)查询。

新增

你将如何调整它包括所有PatientProfiles,不只是那些 并建议计数或审查算?

.joins,而现在你需要LEFT OUTER JOIN产生LEFT INNER JOIN SQL子句。
Rails的5+:

PatientProfile 
    .left_joins(:recommendations, :reviews) 
    # ... 

Rails的< 5作弊:

PatientProfile 
    .eager_load(:recommendations, :reviews) 
    # ... 
+0

谢谢。这很棒。你会如何调整它以包含所有PatientProfiles',而不仅仅是那些带有推荐次数或评论次数的? – user2954587

+0

'.joins'生成'LEFT INNER JOIN' SQL子句,而现在你需要'LEFT OUTER JOIN'。 Rails 5+为此拥有'.left_outer_joins'。 –