基于两个has_many关联的复杂选择

时间:2016-09-27 10:06:34

标签: sql ruby-on-rails postgresql ruby-on-rails-4 activerecord

我有以下模特

帐户

has_many :orders
has_many :account_brands, dependent: :destroy
has_many :brands, through: :account_brands

品牌

  has_many :account_brands, dependent: :destroy
  has_many :accounts, through: :account_brands
  has_many :orders

顺序

belongs_to :account
belongs_to :brand

现在,我想选择所有与该品牌无关的品牌订单。我可以通过循环和检查每个特定的品牌来做到这一点,但它的效率非常低。无法在一次SQL调用中解决如何操作的问题?

只是为了澄清和改写:

我希望所有与该品牌订购的帐户当前未与该帐户相关联

Account1 have brands A,B,C    
Account2 have brands A,B,C


Account1 have order with the brand D -> want this account to be selected
Account2 have order with the brand C -> doesn't care about this one

1 个答案:

答案 0 :(得分:0)

要查找包含与指定帐户无关的品牌订单的帐户,请尝试以下查询,

Account.joins(:brands).joins("LEFT JOIN orders ON (orders.account_id = accounts.id AND orders.brand_id != brands.id)")