活動有屬性:start_date,:end_date
查詢爲參加社團在軌
發票有屬性:start_date,:end_date
campaign.rb
has_many:invoices
invoice.rb
belongs_to:campaign
我想所有這些cmapaigns的start_date
是小於當前日期AND
其end_date
介於campaign.invoices.last.created..current_date
之間
我如何查詢?
活動有屬性:start_date,:end_date
查詢爲參加社團在軌
發票有屬性:start_date,:end_date
campaign.rb
has_many:invoices
invoice.rb
belongs_to:campaign
我想所有這些cmapaigns的start_date
是小於當前日期AND
其end_date
介於campaign.invoices.last.created..current_date
之間
我如何查詢?
試試這個:
Compaign.joins(:invoices)
.where("compaigns.start_date < :today AND compaigns.end_date < :today", today: Date.today)
.group("compaigns.id")
.having("compaigns.end_date > MAX(invoices.created_at)")
我從來沒有使用Rails魔術來執行對數據庫的或多或少複雜的請求。它總是導致劇烈的開銷,N + 1個查詢或者一些意想不到的處罰。這裏是普通的老好版本的SQL執行此任務:
Campaign.connection.execute <<-SQL
SELECT campaigns.*, last_invoice_date
FROM campaigns
JOIN (
SELECT invoices.campaign_id AS campaign_id,
MAX(invoices.started) AS last_invoice_date
FROM invoices
GROUP BY invoices_campaign_id
) AS last_invoices
ON (last_invoices.campaign_id = campaigns.id)
WHERE campaigns.start_date < NOW()
AND campaigns.end_date < NOW()
AND campaigns.end_date >= last_invoices.last_invoice_date
SQL.to_a
上面沒有明顯的原因進行測試,但它應該工作無論是作爲是或略有修改。
campaigns = Campaign.where("DATE(start_date) < ?", Date.today).includes(:invoices)
invoices = campaigns.each do |campaign|
campaign.invoices.where("Date(campaigns.end_date)" BETWEEN campaign.invoices.last.created_at.to_date AND Date.today)
end
invoices.map(&:campaign)
請告訴我們,你嘗試過什麼? – mudasobwa
Campaign.joins(:invoices).where(「campaigns.start_date <?and campaigns.end_date>?」,Time.current,????????) –