5

我有以下模型和关系:

模型图片

一个用户有很多优惠(他/她是卖家),一个优惠有很多购买,一个购买有很多 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 条件。

感谢您的任何见解。

4

3 回答 3

4

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

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

需要知道的是,where使用数据库表的名称。joins(and includes, eager_load, etc) 使用关系名称。这就是为什么我们有:

Admin::Accbook
  .joins(purchase: :offer)
  #                 ^^^^^ relation name
  .where(offers: { seller_id: 123 })
  #      ^^^^^^ table name
于 2018-05-22T13:50:21.243 回答
1

尝试添加以下关联users.rb

has_many :accbooks, through: :purchases

于 2018-05-18T04:36:59.770 回答
0

因此,您的问题是用户充当同一帐户的 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
于 2018-05-18T12:47:09.633 回答