我有3個模型。
class Saving
has_many :contributions
end
class Contribution
belongs_to :saving
has_many :deposits
end
class Deposit
belongs_to :contribution
end
現在我想查詢所有的儲蓄及其貢獻并計算存款的總和.amount。我也想要沒有存款的記錄。
如果我使用
Saving.joins(contributions: [:deposit])
這將給我所有有存款的儲蓄。但我想加入捐款和 left_outer_joins 存款。
我怎樣才能做到這一點?我正在使用 Rails 4。所以我無法做到
Saving.left_outer_joins(contributions: [:deposit]).
uj5u.com熱心網友回復:
在遺留應用程式中執行 OUTER 聯接的最直接方法是使用 SQL 字串:
Saving.select(
'savings.*',
'SUM(deposits.amount) AS total_deposits'
)
.joins(:contributions)
.joins(%q{
LEFT OUTER JOINS depostits
ON depostits.contribution_id = contributions.id
})
您也可以(錯誤)使用.includes外連接:
class Saving
has_many :contributions
has_many :deposits, through: :contributions
end
Saving.includes(:deposits)
.references(:deposits) # forces a single query
.joins(:contributions) # optional - creates an additional inner join
.select(
'savings.*',
'SUM(deposits.amount) AS total_deposits'
)
你也可以使用 Arel:
module LegacyOuterJoiner
# clunky hack for outer joins in legacy apps.
def arel_outer_joins(association_name, fkey = nil)
raise "This method is obsolete! Use left_joins!" if respond_to?(:left_joins)
other_model = reflect_on_association(association_name).klass
right = other_model.arel_table
fkey ||= "#{other_model.model_name.singular}_id".intern
arel_table.joins(right, Arel::Nodes::OuterJoin)
.on(arel_table[fkey].eq(right[:id]))
.join_sources
end
end
class Deposit
extend LegacyOuterJoiner
end
Saving.select(
Saving.arel_table[Arel.star],
Deposit.arel_table[:amount].sum.as('total_deposits')
)
.joins(:contributions)
.joins(Deposit.arel_outer_joins(:contribution))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/315233.html
