I have been trying to figure out how to write this using Eloquent? This is as far as I got, any suggestions?
$budgets = Budget::join('transactions','budgets.id','=','transactions.category')
->where('transactions.user_id','=', $authId)
->groupby('transactions.category')
->sum('budgets.amount','-','transactions.amount');
Query that works below
SELECT SUM(budgets.amount) - SUM(transactions.amount) as amount,
budgets.category
FROM budgets
JOIN transactions
ON budgets.id = transactions.category
GROUP BY category
You were close, but when you're getting multiple columns and math, or semi-complicated math (ie not a simple sum) you want to pass the math along as a separate column in a raw statement.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.