我一直试图弄清楚如何用Eloquent写这个?这是我得到的,有什么建议吗?
$budgets = Budget::join('transactions','budgets.id','=','transactions.category')
->where('transactions.user_id','=', $authId)
->groupby('transactions.category')
->sum('budgets.amount','-','transactions.amount');
在
下面运行的查询 SELECT SUM(budgets.amount) - SUM(transactions.amount) as amount,
budgets.category
FROM budgets
JOIN transactions
ON budgets.id = transactions.category
GROUP BY category
答案 0 :(得分:3)
你很接近,但是当你获得多列和数学,或者半复杂的数学(即不是简单的总和)时,你想要将数学作为原始语句中的单独列传递。
Budgets::join('transactions', 'budgets.id', '=', 'transactions.category')
->select([
DB::raw('SUM(budgets.amount) - SUM(transactions.amount) as amount'),
'budgets.category'
])
->where('transactions.user_id','=', $authId)
->groupBy('budgets.category')
->get();