我已经花了几天时间进行此查询,但仍然没有找到解决方案。
有我的模特
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
我需要选择objects.importance
和总和的查询user_objects.score
。但是我还必须选择仅查询objects
属于user1
和的那些查询user2
。
我写了一个查询来查询选择对象。
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
返回带有字段值的结果数组,因此我们可以从不同的表中选择字段。就是这样。很简单!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句