将sql查询从关联转换为示例方法

axkjgtzd  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(369)

my current user.rb模型

class User < ApplicationRecord
  has_many :children,
           -> (user) { unscope(:where).where("father_id = :id OR mother_id = :id", id: user.id) },
           class_name: "User"

  has_many :grandchildren,
           -> (user) { unscope(:where).where("father_id IN (:ids) OR mother_id IN (:ids)", ids: user.children.ids) },
           class_name: "User"

  belongs_to :mother, class_name: "User", optional: true
  belongs_to :father, class_name: "User", optional: true
end

我的当前数据(空数据为零):

所有查询现在都可以工作了:

但是对于 .grandchildren 查询,您可以看到在控制台中,创建了三个独立的查询。有没有办法只生成一个查询?
我在尝试示例方法,因为我可以输入原始sql,但似乎无法理解它。例如:

def children
    sql = ("SELECT users.* FROM users WHERE (father_id = id OR mother_id = id)")
    p ActiveRecord::Base.connection.execute(sql)
  end
n3ipq98p

n3ipq98p1#

你可以替换

-> (user) { unscope(:where).where("father_id IN (:ids) OR mother_id IN (:ids)", ids: user.children.ids) },

具有

-> (user) do
  scope = unscope(:where)
  children_ids = user.children.select(:id)

  scope
    .where(father_id: children_ids)
    .or(scope.where(mother_id: children_ids))
end

相关问题