【问题标题】:Laravel Eloquent sum throwing errorLaravel Eloquent 总和抛出错误
【发布时间】:2016-08-03 12:01:35
【问题描述】:

我只是想对 column 求和。 我用了这段代码

$money = Income::sum('money');

这个也累了

$money = Income::select(DB::raw('sum(money)'))->get();

但它抛出错误。我使用 postgresql 作为我的数据库。 错误信息:

SQLSTATE[42883]: Undefined function: 7 ERROR: function sum(character varying) does not exist
LINE 1: select sum("money") as aggregate from "incomes"
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts. (SQL: select sum("money") as aggregate from "incomes")

我的桌子:

incomes

+----+---------+-------+
| id | orderid | money |
+----+---------+-------+
|  1 |    2343 |    23 |
|  2 |    2344 |    55 |
+----+---------+-------+

【问题讨论】:

  • 你能发布数据库架构吗?
  • @Jaimin 已编辑帖子
  • 这不是架构;你能发布建立收入表的数据库迁移文件吗?或者使用psql,可以运行\d {income table name}并分享结果吗?
  • 已解决@ChrisForrence。这是我的错。我用列字符串代替整数

标签: php postgresql laravel eloquent


【解决方案1】:

根据您的错误消息,sum 方法不接受 varchar(字符变化)。听起来money 列不是数字数据类型(尽管它完全由数值组成。

要解决此问题,请将值转换为数字数据类型:

Income::select(DB::raw('sum(cast(money as double precision))'))->get()

请注意,这不一定是高效的。您可以考虑更改数据库模式(如果可能)以将货币作为整数和美分存储在数据库中。也就是说,数据库中的 1000 将反映 $10.00。

【讨论】:

    【解决方案2】:

    你可以用这个得到总和

    $money = DB::table('incomes')->sum('money');
    

    查看此链接https://laravel.com/docs/5.0/queries

    【讨论】:

      猜你喜欢
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多