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

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

my current user.rb模型

  1. class User < ApplicationRecord
  2. has_many :children,
  3. -> (user) { unscope(:where).where("father_id = :id OR mother_id = :id", id: user.id) },
  4. class_name: "User"
  5. has_many :grandchildren,
  6. -> (user) { unscope(:where).where("father_id IN (:ids) OR mother_id IN (:ids)", ids: user.children.ids) },
  7. class_name: "User"
  8. belongs_to :mother, class_name: "User", optional: true
  9. belongs_to :father, class_name: "User", optional: true
  10. end

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

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

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

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

n3ipq98p1#

你可以替换

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

具有

  1. -> (user) do
  2. scope = unscope(:where)
  3. children_ids = user.children.select(:id)
  4. scope
  5. .where(father_id: children_ids)
  6. .or(scope.where(mother_id: children_ids))
  7. end

相关问题