简体   繁体   English

Rails 中的多表查询

[英]Multiple table query in Rails

I have done simple Rails finds for two tables, but now find that with a 4 table query I am not making good progress.我已经为两个表完成了简单的 Rails 查找,但现在发现使用 4 个表查询我没有取得好的进展。 All tables are connected with keys and are basically:所有表都用键连接,基本上是:

  • User (has many)用户(有很多)
  • Phones (has many)电话(有很多)
  • Campaigns (has many)广告系列(有很多)
  • Calls来电

I just want to count the total number of calls a specific user has and the total number of calls for a specific campaign.我只想计算特定用户的通话总数以及特定广告系列的通话总数。 I could also add user-id to Campaigns and Calls but for some reason I think that cheating or a bad idea.我也可以将用户 ID 添加到活动和通话中,但出于某种原因,我认为这是作弊或一个坏主意。 I just don't know.我只是不知道。

Rails 3:导轨 3:

Total number of calls a specific user has:特定用户的通话总数:

@user.phones.joins(:campaigns => :calls).count

Total number of calls for a specific campaign:特定活动的总调用次数:

@user.phones.joins(:campaigns => :calls).where('campaigns.id' => @campaign.id).count

Assuming that a phone belongs to a user, and a campaign belongs to a phone:假设一个电话属于一个用户,一个活动属于一个电话:

# total calls for a specific campaign
campaign_call_count = Campaign.find(id).calls.count
# or a report for all campaings
Campaign.all.map{|c| "#{c.name}: #{c.calls.count}"

#total calls a user has
user_phone_ids = user.phones.map(&:id)
user_calls_by_campaign = Campaign.where(:phone_id=>user_phone_ids).map{|campaign| "#{user.name} calls for #{campaign.name}: #{campaign.calls.count}" }
puts user_calls_by_campaign

That should give you a list那应该给你一个清单

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

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