gpt4 book ai didi

sql - 如何使用嵌套关联查询 STI 驱动的模型?

转载 作者:行者123 更新时间:2023-12-04 20:56:17 25 4
gpt4 key购买 nike

我的要求是编写一个查询以根据模型的嵌套关联在 STI 上检索基于模型的记录。

这是我的模型的样子:

class Loan < ApplicationRecord
belongs_to :borrower
end

class BusinessLoan < Loan
belongs_to :business, inverse_of: :business_loans
end

class HousingLoan < Loan
end

class Borrower < ApplicationRecord
has_many :loans
has_one :address, as: :addressable
end

class Business < ApplicationRecord
has_many :business_loans, inverse_of: :business
has_one :address, as: :addressable
end

class Address < ApplicationRecord
# COLUMN city, :string
belongs_to :addressable, polymorphic: true
end

我想写信检索其业务或借款人在特定城市的所有贷款的 list 。

这是我目前所拥有的:

cities = ["New York", "Washington"]

query_string = [
Loan.select(:id).joins(borrower: :address).where(city: cities).to_sql,
BusinessLoan.select(:id).joins(business: :address).where(city: cities).to_sql
].join(" UNION ")
Loan.where(id: Loan.find_by_sql(query_string))

我需要将结果作为 ActiveRecord 关系,因此是最后一个查询

有没有更好的方法来编写这个查询?

最佳答案

看起来没有一种方法可以直接实现这一点,而无需在相关模型中编写一些新范围。 Rails 不允许在作用域中进行任何在启 Action 用域的模型上不可能的操作。

但是,您仍然可以解决该问题以产生单个查询,如下所示:

  • 定义 from_cities Borrower 中的范围和 Business如下图:

  • scope :from_cities, ->(cities) { joins(:address).where("addresses.city IN (?)", cities) }
  • 定义 from_cities在贷款中使用这些新范围:

  • scope :from_cities, ->(cities) do
    where(borrower_id: Borrower.from_cities(cities)).
    or(where(business_id: Business.from_cities(cities)))
    end

    关于sql - 如何使用嵌套关联查询 STI 驱动的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48541287/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com