Activerecord:提取特定的列和关联的关联计数 [英] Activerecord: Pluck specific columns and association's association counts
问题描述
好的,所以我们有个帐户
,其中有许多时间表
,其中有许多展示次数
。
Alright, so we have Accounts
which has many Schedules
which has many Impressions
.
我想获取 Accounts.name
,所有 Accounts.schedules
,但仅采摘 Accounts.schedules.date
, Accounts.schedules.summary
以及 Accounts.schedules.impressions
I want to get Accounts.name
, all of Accounts.schedules
, but only plucking Accounts.schedules.date
, Accounts.schedules.summary
and also the count of Accounts.schedules.impressions
这里是给定1个帐户的可视化视图(我想要所有帐户)
Here's a visualization of what I want given 1 account (I'll want all accounts)
Account:
.name
Schedules
.date
.summary
count(Schedule.impressions)
这是代码看起来好像查询太多了
And here's what the code would look like with too many queries
Account.find_each do |account|
puts a.name # Account.name
a.schedules.each do |schedule|
puts schedule.date # Account.schedule.date
puts schedule.summary # Account.schedule.summary
puts schedule.impressions.count # Count(Account.schedule.impressions)
我想在尽可能少的查询中做到这一点,也许还学到一些东西!我喜欢效率和优化。
I'd like to do this in as few queries as possible, and maybe learn something too! I love efficiency and optimizations.
推荐答案
使用选择查询
Account.
joins(schedules: :impressions).
select("accounts.name as account_name,
schedules.date as schedule_date,
schedules.summary as schedule_summary,
count(impressions.id) as schedule_impression_count" ).
group("accounts.name,schedules.date,schedules.summary")
应该在单个查询中执行此操作,对象将响应列别名,如 schedule_date
和 schedule_impression_count
Should do it in a single query then the objects will respond the the column alias' like schedule_date
and schedule_impression_count
如果您需要在同一视图中将这些对象用于其他数据,则 Account.eager_load(schedules::impressions)
也应工作,并且还将执行一个查询。
If you need to use these objects for other data in the same view then Account.eager_load(schedules: :impressions)
should also work and will also execute a single query.
这篇关于Activerecord:提取特定的列和关联的关联计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!