加入嵌套关联(多级)

Joining Nested Associations (Multiple Level)

我有以下模型和关系:

一个用户有很多报价(其中 he/she 是卖家),一个报价有很多购买,一个购买有很多 Accbooks

模型和协会:

class User < ApplicationRecord
  has_many :offers, foreign_key: :seller_id
  has_many :purchases, foreign_key: :buyer_id
end

class Offer < ApplicationRecord
  has_many :purchases
  belongs_to :seller, class_name: 'User'
end

class Purchase < ApplicationRecord
  belongs_to :offer
  belongs_to :buyer, class_name: 'User'
  has_one :seller, through: :offer
  has_many :accbooks,  class_name: 'Admin::Accbook', foreign_key: 'purchase_id' 
end

module Admin
  class Accbook < ApplicationRecord
    belongs_to :purchase
  end
end  

我想获取任何给定用户(作为卖家)的所有 Accbooks。等效的 SQL 语句如下所示:

SELECT  "accbooks".* 
FROM "accbooks" 
INNER JOIN "purchases" ON "purchases"."id" = "accbooks"."purchase_id"
INNER JOIN "offers" ON "offers"."id" = "purchases"."offer_id"
INNER JOIN "users" ON "users"."id" = "offers"."seller_id"
WHERE "users"."id" = ?

到目前为止我试过这个:

Admin::Accbook.joins( {purchase: :offer} )

结果是 SQL:

SELECT  "accbooks".*
FROM "accbooks"
INNER JOIN "purchases" ON "purchases"."id" = "accbooks"."purchase_id"
INNER JOIN "offers" ON "offers"."id" = "purchases"."offer_id"

现在我不知道如何将连接添加到用户模型,然后如何添加 Where 条件。

感谢您的任何见解。

尝试在 users.rb

中添加以下关联

has_many :accbooks, through: :purchases

所以您的问题是用户在同一帐户中充当 2 个角色。你可以试试下面的东西

class User < ApplicationRecord
  has_many :offers, foreign_key: :seller_id
  has_many :purchases, foreign_key: :buyer_id
  has_many :offers_purchases,
           through: :offers,
           :class_name => 'Purchase',
           :foreign_key => 'offer_id',
           :source => :purchases
end

您可以 joins 将这些关系放在一起并在连接的关系上应用 where 子句:

Admin::Accbook
  .joins(purchase: :offer)
  .where(offers: { seller_id: 123 })

需要注意的是,where 使用数据库 table 的名称。 joins(以及 includeseager_load 等)使用关系名称。这就是为什么我们有:

Admin::Accbook
  .joins(purchase: :offer)
  #                 ^^^^^ relation name
  .where(offers: { seller_id: 123 })
  #      ^^^^^^ table name