Reputation: 189
How can I calculate the value of two columns using Laravel 5 query?
Example of my DB structure.
+--------+--------+
| value1 | value2 |
+--------+--------+
| 30 | 30 |
+--------+--------+
| 10 | 10 |
+--------+--------+
| 5 | 25 |
+--------+--------+
I want to get the total value of value1 + value2
I've tried something like this, but it didn't work.
$topUsers = DB::table('users_stats')->orderBy('value1 '+' value2', 'desc')->limit(3)->get();
This way I get this error:
ErrorException in HomeController.php line 39:
A non-numeric value encountered
Expected output:
60
20
30
Upvotes: 0
Views: 2246
Reputation: 166
Using collections
$topUsers = DB::table('users_stats')->limit(3)->get()
->transform(function ($item) {
return $item->value1 + $item->value2;
});
Laravel Collections: Transform
Upvotes: 0
Reputation: 13259
Try
$topUsers = DB::table('users_stats')
->groupBy('id')
->orderByRaw('SUM(value1 + value2) DESC')
->limit(3)
->get();
Upvotes: 2