簡體   English   中英

ActiveRecord:具有“求和”,“合並”,“分組依據”和“選擇多個字段”的復雜查詢

[英]ActiveRecord: complex query with Sum, Join, Group By and Select multiple fields

我已經花了幾天時間進行此查詢,但仍然沒有找到解決方案。

有我的模特

class UserObject < ActiveRecord::Base
  self.table_name = "user_objects"
  belongs_to :user, class_name: 'User'
  belongs_to :the_object, class_name: 'Object'
end

class Object < ActiveRecord::Base
  self.table_name = 'objects'

  has_many :user_objects, class_name: 'UserObject', foreign_key: :the_object_id, inverse_of: :the_object
  has_many :users, through: :user_objects
end

class User < ActiveRecord::Base
  self.table_name = "users"
end

這是我的圖式

  create_table "objects", force: true do |t|
    t.float    "importance",        default: 0.5, null: false
  end

  create_table "user_objects", force: true do |t|
    t.integer  "user_id"
    t.integer  "the_object_id"
    t.float    "score",              default: 0.0,   null: false
  end

  create_table "users", force: true do |t|
    t.string   "first_name"
    t.string   "last_name"
  end

我需要查詢select objects.importanceuser_objects.score總和。 但是我還必須選擇僅查詢屬於user1user2那些objects

我寫了一個查詢選擇對象。

Object.select("objects.importance").joins(:user_objects).
                                    where(user_objects: {user_id: [user1_id,user2_id]}).
                                    group(objects: :id).
                                    having('COUNT("user_objects"."id")=2')

並轉換為

SELECT objects.importance FROM "objects" INNER JOIN "user_objects" ON "user_objects"."the_object_id" = "objects"."id" WHERE "user_objects"."user_id" IN (2, 7) GROUP BY "objects"."id" HAVING COUNT("user_objects"."id")=2

當我執行此查詢時,我得到了這個響應

[#<Object id: nil, importance: 0.5>, #<Object id: nil, importance: 0.5>]

可以響應的對象數量可以。 但是我仍然不知道如何在user_objects.score這個查詢總數中進行計數。 下一個查詢不起作用

Object.select("objects.importance, SUM(user_objects.score)").
       joins(:user_objects).
       where(user_objects: {user_id: [user1_id,user2_id]}).
       group(objects: :id).having('COUNT("user_objects"."id")=2')

我期望這樣的回應

[#[<Object id: nil, importance: 0.5>, 0.2], #[<Object id: nil, importance: 0.5>,0.3]]

我將非常感謝您在解決此問題方面可以給我的任何幫助。

Ок。 我找到了解決方案。 這是正確的查詢。

Object.joins(:user_objects).
       where(user_objects: {user_id: [user1_id,user2_id]}).
       group(objects: :id).
       having('COUNT("user_objects"."id")=2').
       pluck("objects.importance, SUM(user_objects.score)")

select方法存在問題,因為它創建調用此方法的類的對象 因此,不可能在少數幾個模型的一個select屬性中進行選擇。 pluck回報產生與字段的數組所以我們可以選擇從不同的表中的字段。 就是這樣。 很簡單!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM