我有一個表invoices
和invoices
belongs_to :subscription
和subscription
belongs_to :user
。 A user
has_many :licenses
。我需要兩個查詢,其中一個獲取在特定時間段內創建的所有invoices
,其中包含licenses
,因此那些licenses
沒有特定的viewership_id
。Complex ActiveRecord加入
我能得到這個查詢正確的,那就是:
Invoice.joins(
subscription: {
user: :licenses
}
).where(
# Other licenses during date range
licenses: {
created_at: date_range
}
).where.not(
licenses: {
viewership_id: Viewership.member.tier(1).first.id
}
)
現在,我需要一個查詢,得到所有的invoices
不具有在特定時間段內創建的任何許可證。像這樣的東西(儘管這不工作):
Invoice.includes(
subscription: {
user: :licenses
}
).where(
licenses: {
user_id: nil,
created_at: date_range # <-- removing this works, but is an incorrect query,
# because the user may have created other
# licenses outside of this date_range and
# that's alright--so querying without the
# date_range means i may miss some users who
# have licenses that just weren't created in
# the date_range
}
)
我很難搞清楚你想要什麼,特別是那條評論。如果您可以創建一個顯示您嘗試實現的許可證的小型可視表,它可能會有所幫助。我也有點困惑 - 如果你想要的是許可證,爲什麼你不從許可證開始查詢? – max
@max我說我需要一些發票,而不是許可證。我會盡力寫出一張圖 – trevorhinesley
對不起,我的不好。您是否考慮在發票和許可證之間建立較少的切線關係?除了速度慢以外,你加入3張桌子的事實似乎是一種真正的代碼味道。 – max