dongyanfeng0546 2016-08-03 04:01
浏览 94
已采纳

Laravel Eloquent总和抛出错误

I'm just simply want to sum column . I used this code

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

also tired this

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

but it's throwing error . I'm using postgresql as my database . Error message :

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")

my table :

incomes

+----+---------+-------+
| id | orderid | money |
+----+---------+-------+
|  1 |    2343 |    23 |
|  2 |    2344 |    55 |
+----+---------+-------+
  • 写回答

2条回答 默认 最新

  • dpvomqeu396484 2016-08-03 04:28
    关注

    According to your error message, the sum method doesn't take in a varchar (character varying). It sounds like the money column is not a number datatype (though it my solely consist of numeric values.

    To work around this, cast the value to a numeric data type:

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

    Note that this will not necessarily be performant. You may consider changing the database schema (if possible) to store money as an integer and as cents in the database. That is, 1000 in the database would reflect $10.00.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部