【问题标题】:Active Record - Get records where association doesn't exists [duplicate]Active Record - 获取不存在关联的记录[重复]
【发布时间】:2018-01-16 08:32:02
【问题描述】:

我有一个模型A,它有我的B 模型的_many(所以B 模型用foreign_key a_id 引用A)。 我想获取任何 B 记录未引用的所有 A 记录。使用活动记录更有效的方法是什么? 谢谢!

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    从 Rails 5 开始:

    A.left_outer_joins(:bs).where(bs: { a_id: nil })
    

    SQL 的输出是:

    SELECT "as".* FROM "as"
    LEFT OUTER JOIN "bs" ON "bs"."a_id" = "a"."id"
    WHERE "bs.a_id" IS NULL
    

    【讨论】:

    【解决方案2】:

    我认为你的模型看起来像

    class A < ApplicationRecord
      has_may :bs
    end
    
    class B < ApplicationRecord
      belongs_to :a
    end
    

    我认为您的 schema.rb 看起来像

      create_table "as", force: :cascade do |t|
        t.integer  "id"
        t.datetime "created_at",  null: false
        t.datetime "updated_at",  null: false
      end
    
      create_table "bs", force: :cascade do |t|
        t.integer  "id"
        t.integer  "a_id"
        t.datetime "created_at",  null: false
        t.datetime "updated_at",  null: false
      end
    

    如果我有这个权利,那么你应该可以做到

    A.where.not(id: B.select(:a_id))
    

    【讨论】:

      【解决方案3】:

      详细信息可能取决于您的数据库、您创建的索引和您存储的数据,但我建议您尝试使用子查询:

      A.where.not(id: B.select(:a_id))
      

      在 PostgreSQL 上,这将导致 单个查询,例如:

      SELECT * FROM as WHERE id NOT IN (SELECT a_id FROM bs)
      

      【讨论】:

      • 这正是我需要的!很快就会接受答案。谢谢
      • 谢谢你,@RonanLopes!如果在您的情况下查询太慢,请发布更新,我很乐意帮助您调整它。 :-)
      猜你喜欢
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 2015-05-17
      • 2012-10-24
      • 2017-12-04
      • 2023-03-21
      相关资源
      最近更新 更多