Udhayan Nair
Udhayan Nair

Reputation: 552

How do I build a sum() query in Laravel with the add and subtract operators?

so I have a query as such;

select sum(points_add) as total_add, sum(points_subtract) as total_deducts, (sum(points_add)-sum(points_subtract)) as total_balance from tbl_points where user_id = 2;

How do I build it in Laravel? I know how to do it up until the (sum(points_add)-sum(points_subtract)) as total_balance part as I'm not sure how to query out the "-" subtract function.

Upvotes: 0

Views: 2142

Answers (1)

Rwd
Rwd

Reputation: 35180

For this the easiest thing would be to use selectRaw():

$values = DB::table('tbl_points')
    ->selectRaw('sum(points_add) as total_add, sum(points_subtract) as total_deducts, (sum(points_add)-sum(points_subtract)) as total_balance')
    ->where('user_id', 2)
    ->first();

Laravel does come with aggregates(), however, these are used to return single values instead of multiple aggregates.

Upvotes: 2

Related Questions