抱歉標題含糊。我有 3 個表:User、Place 和 PlaceOwner。我想在“PlaceOwner”模型中撰寫一個范圍來獲取所有沒有所有者的“Places”。
class User < ApplicationRecord
has_one :place_owner
end
class PlaceOwner < ApplicationRecord
belongs_to :user
belongs_to :place
#scope :places_without_owner, -> {}
class Place < ApplicationRecord
has_many :place_owners
end
我嘗試在 Rails 控制臺中檢查每個元素的關聯并且它有效。但我不知道如何在范圍內實作這一點。我見過人們通過撰寫 SQL 來解決類似的問題,但我不具備這樣撰寫它的知識。我了解我需要檢查 Place 中的所有 ID 以查看它們是否在 PlaceOwner 表中。但我無法實施。
例如:
“地點”表中有 3 條記錄:House13, House14, House15。
“PlaceOwner”表中有 2 條記錄:House13 - User1 , House 14 - User2
我要買House15
我希望我清楚地解釋了我想要做什么。請幫助或至少告訴我去哪里。提前致謝!
uj5u.com熱心網友回復:
我會使用ActiveRecord::QueryMethods::WhereChain#missingRuby on Rails 6.1 中引入的方法:
Place.where.missing(:place_owners)
從檔案中參考:
missing(*associations)回傳帶有左外連接和 where 子句的新關系以識別缺失的關系。
例如,缺少相關作者的帖子:
Post.where.missing(:author) # SELECT "posts".* FROM "posts" # LEFT OUTER JOIN "authors" ON "authors"."id" = "posts"."author_id" # WHERE "authors"."id" IS NULL
uj5u.com熱心網友回復:
在舊版本中:
Place.includes(:place_owners).where(place_owners: { id: nil })
Place.left_joins(:place_owners).where(place_owners: { id: nil })
另一個有趣的選擇是使用EXISTS. 很多時候這樣的查詢有更好的性能,但不幸的是 rails 還沒有這樣的特性(參見這里和這里的討論)
Place.where_not_exists(:place_owners)
Place.where_assoc_not_exists(:place_owners)
要使用這些方法,您需要使用where_exists或activerecord_where_assocgem
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521329.html
上一篇:golang中的輸入驗證
