Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 200
Andrew Avatar asked Mar 03 '17 05:03

Andrew


People also ask

How write raw SQL query in laravel?

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection. Since the query builder is using PDO in the background, we know there is a way to bind parameters to our query so it will sanitize the bound variables.


2 Answers

$query = YourModel::query();
$query->withCount([
'activity AS yoursum' => function ($query) {
        $query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
    }
]);
like image 104
ahmad ali Avatar answered Sep 29 '22 06:09

ahmad ali


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

like image 41
Sagar Arora Avatar answered Sep 29 '22 04:09

Sagar Arora