dongyanfeng0546 2016-08-03 12: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 12: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条)

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏