Andrew
Andrew

Reputation: 451

Laravel Sum column database Eloquent

Trying to get the sum of a int field in one of my table should be pretty easy, unfortunately it is not as I'm getting different result whether I use Laravel, MySQL or Excel.

Laravel 5.4 gives me 20506:

Table::sum('field_name');

MySQL gives me 1830:

Select sum(field_name) from table;

And the data from the Excel sheet before importing it into the database: Sum gives me 145689

Any idea? I tried to cast to integer before doing the sum but it doesn't work. All the numbers are pretty big but don't contain comma or dot.

Examples of values I have to sum: (contain sometimes empty cells)

17906774
99630157
28581131

159551532
20312892
668928885

Upvotes: 6

Views: 34958

Answers (3)

ahmad ali
ahmad ali

Reputation: 1245

$query = YourModel::query();
$query->withCount([
'activity AS yoursum' => function ($query) {
        $query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
    }
]);

Upvotes: 5

Sagar Arora
Sagar Arora

Reputation: 1773

You can use laravel aggregate function SUM as :

$result = DB::table('table_name')
                ->select(DB::raw('SUM(field_name) as total_field_name'))
                ->get();

For more details you can follow:

https://laravel.com/docs/5.4/queries

Thanks

Upvotes: 5

EddyTheDove
EddyTheDove

Reputation: 13259

Try with

$result = DB::table(tablename)
->selectRaw('sum(column)')
->get();

If it still gives you wrong result, maybe wait for someone to give you a better answer. This is all I could think of.

Upvotes: 1

Related Questions