跳至内容 跳至搜索

Active Record 计算

方法
A
C
I
M
P
S

实例公共方法

async_average(column_name)

average 相同,但异步执行查询并返回一个 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 122
def async_average(column_name)
  async.average(column_name)
end

async_count(column_name = nil)

count 相同,但异步执行查询并返回一个 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 108
def async_count(column_name = nil)
  async.count(column_name)
end

async_ids()

ids 相同,但异步执行查询并返回一个 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 409
def async_ids
  async.ids
end

async_maximum(column_name)

maximum 相同,但异步执行查询并返回一个 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 152
def async_maximum(column_name)
  async.maximum(column_name)
end

async_minimum(column_name)

minimum 相同,但异步执行查询并返回一个 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 137
def async_minimum(column_name)
  async.minimum(column_name)
end

async_pick(*column_names)

pick 相同,但异步执行查询并返回一个 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 363
def async_pick(*column_names)
  async.pick(*column_names)
end

async_pluck(*column_names)

pluck 相同,但异步执行查询并返回一个 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 334
def async_pluck(*column_names)
  async.pluck(*column_names)
end

async_sum(identity_or_column = nil)

sum 相同,但异步执行查询并返回一个 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 182
def async_sum(identity_or_column = nil)
  async.sum(identity_or_column)
end

average(column_name)

计算给定列的平均值。如果没有行,则返回 nil。有关选项的示例,请参见 calculate

Person.average(:age) # => 35.8
# File activerecord/lib/active_record/relation/calculations.rb, line 116
def average(column_name)
  calculate(:average, column_name)
end

calculate(operation, column_name)

这计算给定列中的聚合值。方法为 countsumaverageminimum,和 maximum 已作为快捷方式添加。

Person.calculate(:count, :all) # The same as Person.count
Person.average(:age) # SELECT AVG(age) FROM people...

# Selects the minimum age for any family without any minors
Person.group(:last_name).having("min(age) > 17").minimum(:age)

Person.sum("2 * age")

输出有两种基本形式

  • 单个聚合值:单个值为 COUNT 类型转换为 Integer,AVG 类型转换为 Float,其他所有值类型转换为给定列的类型。

  • 分组值:这将返回值的排序哈希并对其进行分组。它接受列名或 belongs_to 关联的名称。

    values = Person.group('last_name').maximum(:age)
    puts values["Drake"]
    # => 43
    
    drake  = Family.find_by(last_name: 'Drake')
    values = Person.group(:family).maximum(:age) # Person belongs_to :family
    puts values[drake]
    # => 43
    
    values.each do |family, max_age|
      ...
    end
    
# File activerecord/lib/active_record/relation/calculations.rb, line 217
def calculate(operation, column_name)
  operation = operation.to_s.downcase

  if @none
    case operation
    when "count", "sum"
      result = group_values.any? ? Hash.new : 0
      return @async ? Promise::Complete.new(result) : result
    when "average", "minimum", "maximum"
      result = group_values.any? ? Hash.new : nil
      return @async ? Promise::Complete.new(result) : result
    end
  end

  if has_include?(column_name)
    relation = apply_join_dependency

    if operation == "count"
      unless distinct_value || distinct_select?(column_name || select_for_count)
        relation.distinct!
        relation.select_values = Array(model.primary_key || table[Arel.star])
      end
      # PostgreSQL: ORDER BY expressions must appear in SELECT list when using DISTINCT
      relation.order_values = [] if group_values.empty?
    end

    relation.calculate(operation, column_name)
  else
    perform_calculation(operation, column_name)
  end
end

count(column_name = nil)

计算记录数。

Person.count
# => the total count of all people

Person.count(:age)
# => returns the total count of all people whose age is present in database

Person.count(:all)
# => performs a COUNT(*) (:all is an alias for '*')

Person.distinct.count(:age)
# => counts the number of different age values

如果 countRelation#group 一起使用,它将返回一个 Hash,其键表示聚合列,值是相应的值。

Person.group(:city).count
# => { 'Rome' => 5, 'Paris' => 3 }

如果 countRelation#group 一起使用以用于多个列,它将返回一个 Hash,其键是一个数组,包含每列的各个值,每个键的值是 count

Article.group(:status, :category).count
# =>  {["draft", "business"]=>10, ["draft", "technology"]=>4, ["published", "technology"]=>2}

如果 countRelation#select 一起使用,它将计算选定的列。

Person.select(:age).count
# => counts the number of different age values

注意:并非所有有效的 Relation#select 表达式都是有效的 count 表达式。具体内容因数据库而异。在无效情况下,将抛出数据库错误。

如果给定一个块,则加载关系中的所有记录(如果关系尚未加载)。使用关系中的每个记录调用块。返回块返回真值记录的数量。

Person.count { |person| person.age > 21 }
# => counts the number of people older that 21

注意:如果关系中有很多记录,加载所有记录可能会导致性能问题。

# File activerecord/lib/active_record/relation/calculations.rb, line 94
def count(column_name = nil)
  if block_given?
    unless column_name.nil?
      raise ArgumentError, "Column name argument is not supported when a block is passed."
    end

    super()
  else
    calculate(:count, column_name)
  end
end

ids()

使用表的 ​​主键返回关系的基本模型的 ID。

Person.ids # SELECT people.id FROM people
Person.joins(:company).ids # SELECT people.id FROM people INNER JOIN companies ON companies.id = people.company_id
# File activerecord/lib/active_record/relation/calculations.rb, line 371
def ids
  primary_key_array = Array(primary_key)

  if loaded?
    result = records.map do |record|
      if primary_key_array.one?
        record._read_attribute(primary_key_array.first)
      else
        primary_key_array.map { |column| record._read_attribute(column) }
      end
    end
    return @async ? Promise::Complete.new(result) : result
  end

  if has_include?(primary_key)
    relation = apply_join_dependency.group(*primary_key_array)
    return relation.ids
  end

  columns = arel_columns(primary_key_array)
  relation = spawn
  relation.select_values = columns

  result = if relation.where_clause.contradiction?
    ActiveRecord::Result.empty
  else
    skip_query_cache_if_necessary do
      model.with_connection do |c|
        c.select_all(relation, "#{model.name} Ids", async: @async)
      end
    end
  end

  result.then { |result| type_cast_pluck_values(result, columns) }
end

maximum(column_name)

计算给定列上的最大值。值将以与列相同的​​数据类型返回,如果没有行,则返回 nil。有关选项的示例,请参见 calculate

Person.maximum(:age) # => 93
# File activerecord/lib/active_record/relation/calculations.rb, line 146
def maximum(column_name)
  calculate(:maximum, column_name)
end

minimum(column_name)

计算给定列上的最小值。值将以与列相同的​​数据类型返回,如果没有行,则返回 nil。有关选项的示例,请参见 calculate

Person.minimum(:age) # => 7
# File activerecord/lib/active_record/relation/calculations.rb, line 131
def minimum(column_name)
  calculate(:minimum, column_name)
end

pick(*column_names)

从当前关系中的命名列中挑选值。这是 relation.limit(1).pluck(*column_names).first 的简写,主要在关系已缩小到单行时有用。

就像 pluck 一样,pick 只会加载实际值,而不是整个记录对象,因此效率更高。与 pluck 一样,值也会通过列类型进行类型转换。

Person.where(id: 1).pick(:name)
# SELECT people.name FROM people WHERE id = 1 LIMIT 1
# => 'David'

Person.where(id: 1).pick(:name, :email_address)
# SELECT people.name, people.email_address FROM people WHERE id = 1 LIMIT 1
# => [ 'David', '[email protected]' ]
# File activerecord/lib/active_record/relation/calculations.rb, line 352
def pick(*column_names)
  if loaded? && all_attributes?(column_names)
    result = records.pick(*column_names)
    return @async ? Promise::Complete.new(result) : result
  end

  limit(1).pluck(*column_names).then(&:first)
end

pluck(*column_names)

使用 pluck 作为快捷方式来选择一个或多个属性,而无需为每行加载整个记录对象。

Person.pluck(:name)

而不是

Person.all.map(&:name)

Pluck 返回一个 Array,其中包含类型转换为与所选列名匹配的属性值(如果可以推断)。默认情况下,选取 SQL 片段将返回 String 值。

Person.pluck(:name)
# SELECT people.name FROM people
# => ['David', 'Jeremy', 'Jose']

Person.pluck(:id, :name)
# SELECT people.id, people.name FROM people
# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]

Person.distinct.pluck(:role)
# SELECT DISTINCT role FROM people
# => ['admin', 'member', 'guest']

Person.where(age: 21).limit(5).pluck(:id)
# SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
# => [2, 3]

Comment.joins(:person).pluck(:id, person: :id)
# SELECT comments.id, person.id FROM comments INNER JOIN people person ON person.id = comments.person_id
# => [[1, 2], [2, 2]]

Comment.joins(:person).pluck(:id, person: [:id, :name])
# SELECT comments.id, person.id, person.name FROM comments INNER JOIN people person ON person.id = comments.person_id
# => [[1, 2, 'David'], [2, 2, 'David']]

Person.pluck(Arel.sql('DATEDIFF(updated_at, created_at)'))
# SELECT DATEDIFF(updated_at, created_at) FROM people
# => ['0', '27761', '173']

另请参见 ids

# File activerecord/lib/active_record/relation/calculations.rb, line 291
def pluck(*column_names)
  if @none
    if @async
      return Promise::Complete.new([])
    else
      return []
    end
  end

  if loaded? && all_attributes?(column_names)
    result = records.pluck(*column_names)
    if @async
      return Promise::Complete.new(result)
    else
      return result
    end
  end

  if has_include?(column_names.first)
    relation = apply_join_dependency
    relation.pluck(*column_names)
  else
    model.disallow_raw_sql!(flattened_args(column_names))
    relation = spawn
    columns = relation.arel_columns(column_names)
    relation.select_values = columns
    result = skip_query_cache_if_necessary do
      if where_clause.contradiction?
        ActiveRecord::Result.empty(async: @async)
      else
        model.with_connection do |c|
          c.select_all(relation.arel, "#{model.name} Pluck", async: @async)
        end
      end
    end
    result.then do |result|
      type_cast_pluck_values(result, columns)
    end
  end
end

sum(initial_value_or_column = 0, &block)

计算给定列上值的总和。值将以与列相同的​​数据类型返回,如果没有行,则返回 0。有关选项的示例,请参见 calculate

Person.sum(:age) # => 4562

如果给定一个块,则加载关系中的所有记录(如果关系尚未加载)。使用关系中的每个记录调用块。返回 initial_value_or_column 和块返回值的总和。

Person.sum { |person| person.age } # => 4562
Person.sum(1000) { |person| person.age } # => 5562

注意:如果关系中有很多记录,加载所有记录可能会导致性能问题。

# File activerecord/lib/active_record/relation/calculations.rb, line 172
def sum(initial_value_or_column = 0, &block)
  if block_given?
    map(&block).sum(initial_value_or_column)
  else
    calculate(:sum, initial_value_or_column)
  end
end