Arnas Pecelis
Arnas Pecelis

Reputation: 35

get sum of all entries by column in laravel

So I have table prices with structure:

+----+--------+
| id | reward |
+----+--------+
| 1  | 721    |
+----+--------+
| 2  | 54     |
+----+--------+
| 3  | 99     |
+----+--------+

and I'm using this method to sum all rewards:

'withdrawals' => \App\Tradeoffer::where('type', 'withdraw')
            ->where('completed', 1)
            ->where('declined', 0)
            ->where('timeout', 0)
            ->where('created_at', '>', (time() - $hours))
            ->sum('reward')

and the response is: 7215499 instead of sum of all entries. Why is that? How to deal with it?

Upvotes: 1

Views: 3979

Answers (3)

Itipacs
Itipacs

Reputation: 182

Instead of use the model I use a Query Builder and it works (with my database)

DB::table('Tradeoffer') // Here is the name of the table
    ->where('type', 'withdraw')
    ->where('completed', 1)
    ->where('declined', 0)
    ->where('timeout', 0)
    ->where('created_at', '>', (time() - $hours))
    ->sum('reward');

Try it!

Upvotes: 1

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

I think you can do it like,

$totalReward = \App\Tradeoffer::selectRaw('SUM(reward) as total')
        ->where('type', 'withdraw')
        ->where('completed', 1)
        ->where('declined', 0)
        ->where('timeout', 0)
        ->where('created_at', '>', (time() - $hours))
        ->first();

$totalReward->total;

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

What you should do is making sure your reward column in prices table in database is number (integer/float) and not varchar

Upvotes: 0

Related Questions