我想查询将结果添加到数组的查询,例如:
query = self.patients.where(["created_at >= ? and created_at >= ? and created_at >= ?", Time.zone.now.beginning_of_day, Time.now.beginning_of_week, Time.now.beginning_of_month]).to_a
query
=> [3, 5, 12]
Patient Load (0.8ms) SELECT `patients`.* FROM `patients` WHERE `patients`.`medic_id` = 1 AND (created_at >= '2018-07-20 00:00:00' and created_at >= '2018-07-16 05:00:00' and created_at >= '2018-07-01 05:00:00')
=> #<ActiveRecord::AssociationRelation []>
without to_a method => [#<ActiveRecord::AssociationRelation []>]
with to_a method => []
class User < ApplicationRecord
has_many :patients, dependent: :destroy
end
class Patient < ApplicationRecord
belongs_to :user
end
我接收到一个空数组/ AssociationRelation,如何获得像query = [3, 5, 12]
这样的数组,其中包含每天,每周,每月开始时的患者计数?
注意,使用:
答案 0 :(得分:2)
class Patient < ApplicationRecord
scope :created_since, -> (time) { where('created_at >= ?', time) }
# ...
end
我如何获得一天,周,月开始时的患者计数数组,例如此查询= [3,5,12]?
patients_counts = [
Patient.created_since(Time.zone.now.beginning_of_day).count,
Patient.created_since(Time.zone.now.beginning_of_week).count,
Patient.created_since(Time.zone.now.beginning_of_month).count,
]
puts patients_counts
# => [3, 5, 12]
@user.patients.created_since(...)
P.S。我不建议在一个查询中进行操作,而只是像上面那样进行三个单独的计数查询。您可以在一个查询中执行此操作,但必须编写一个非常特定的SQL,并且会变得很丑,因为您需要三个子查询(据我所见)。
答案 1 :(得分:0)
另一种解决方案是使用SQL UNION
运算符来组合3组不同的记录,这些记录由不同的时间戳过滤。您可以在这篇文章中阅读如何获得这样的结果:ActiveRecord Query Union