[英]Rails complex joins query
這是我的基本模型層次結構:
class Product
has_many :inventories
end
class Inventory
belongs_to :product
has_many :inventory_events
end
class InventoryEvent
belongs_to :inventory
end
InventoryEvent實例存儲狀態更改+那些更改的時間戳,因此inventory.inventory_events.last
顯示當前狀態。
我在針對Product模型創建查詢時遇到了問題,該查詢將為我提供received
其當前狀態的所有清單。
我現在所擁有的是:
p = Product.first
p.inventories.joins(:inventory_events).where(inventory_events: {state: 'received'}).all
=> # Here I get back all Inventory that ever had the state 'received' but may
not currently be 'received'.
我的SQL知識是非常有限的,但是似乎對inventory_events: {}
某種限制inventory_events: {}
選項可能有效,但是還沒有找到一種方法。
編輯:這是我目前的解決方法,只是為了顯示我的最終目標。 希望有一種方法可以對這樣的查詢建模。
class Inventory
def self.received_items
includes(:inventory_events).select {|i| i.current_state == 'received'}
end
def current_state
inventory_events.last.state
end
end
Product.first.inventories.received_items
=> # Here I get the correct array of inventories
您可以通過使用范圍和合並方法來完成此操作。 范圍將使您可以將where條件保持模塊化。 通過merge方法,您可以選擇接收到InventoryEvent的Inventory。
# call this to get the inventories for the product that have been recieved
product.inventories.received
class InventoryEvent
def self.received
where("state = ?", "received")
end
def self.most_recent
order("inventory_events.created_at desc").first
end
end
class Inventory
def self.received
joins(:inventory_events).
merge(InventoryEvent.received).
merge(InventoryEvent.most_recent)
end
end
我發現了這段SQL,它一直在為我工作:
joins(:inventory_events).where("inventory_events.id IN (SELECT MAX(id) FROM inventory_events GROUP BY inventory_id) AND state = 'received'")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.