Rails:如何查找没有关联记录的相同模型关联记录



给定:

class Account < ApplicationRecord
belongs_to :super_account, class_name: 'Account', optional: true, foreign_key: 'account_id'
has_many   :sub_accounts,  class_name: 'Account'
end

查找所有没有sub_accounts帐户的轨道方法是什么?

Account.left_joins(:sub_accounts)
.where(sub_accounts_accounts: { id: nil })

sub_accounts_accounts是联接表在查询中的别名:

SELECT "accounts".* FROM "accounts" 
LEFT OUTER JOIN "accounts" "sub_accounts_accounts" 
ON "sub_accounts_accounts"."account_id" = "accounts"."id" 
WHERE "sub_accounts_accounts"."id" IS NULL LIMIT $1

.left_joins(又名左外连接(是在 Rails 5 中引入的。在 Rails 4 中,您需要将.joins与 sql 字符串一起使用。

Account.joins(%q{
LEFT OUTER JOIN accounts sub_accounts
ON sub_accounts.account_id = accounts.id
}).where(sub_accounts: { id: nil })

Rails 的方法是将:counter_cache添加到此关联中。如何

因此,您需要将列sub_accounts_count添加到Account并在模型SubAccount中添加counter_cache: true

belongs_to :account, counter_cache: true

在此之后,您可以调用Account.where(sub_accounts_count: 0)作为示例。

最新更新