加入嵌套关联(多级)

时间:2018-05-17 23:13:36

标签: ruby-on-rails activerecord ruby-on-rails-5 queryinterface

我有以下模特和关系:

Picture of models

用户有许多优惠(他/她是卖家),优惠有很多购买,购买有很多优惠簿

模特和协会:

const commando = require('discord.js-commando');
const prefix = ":D";
const bot = new commando.Client({
    commandPrefix: prefix
});

bot.registry.registerGroup('random', 'Random');
bot.registry.registerCommandsIn(__dirname + "/commands");

bot.login('Botcode'
);

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

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  

到目前为止,我已经尝试过这个:

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" = ?

这给了我这个SQL的结果:

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

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

感谢您的任何见解。

3 个答案:

答案 0 :(得分:1)

尝试在@Query

中添加以下关联

users.rb

答案 1 :(得分:1)

您可以joins将关系放在一起并对联合关系应用where条款:

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

要知道的是,where使用数据库表的名称。 joins(和includeseager_load等)使用关系名称。这就是为什么我们有:

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

答案 2 :(得分: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