Laravel Sum 列数据库 Eloquent

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42571650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:27:38  来源:igfitidea点击:

Laravel Sum column database Eloquent

mysqllaraveleloquent

提问by Andrew

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.

尝试在我的一个表中获取 int 字段的总和应该很容易,不幸的是,无论我使用 Laravel、MySQL 还是 Excel,我都不会得到不同的结果。

Laravel 5.4 gives me 20506:

Laravel 5.4 给了我20506

Table::sum('field_name');

MySQL gives me 1830:

MySQL 给了我1830

Select sum(field_name) from table;

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

以及将 Excel 工作表中的数据导入数据库之前:Sum 给了我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

回答by ahmad ali

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

回答by EddyTheDove

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.

如果它仍然给你错误的结果,也许等待有人给你一个更好的答案。我能想到的就这些。

回答by Sagar Arora

You can use laravel aggregate function SUM as :

您可以将 Laravel 聚合函数 SUM 用作:

$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

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

Thanks

谢谢