duanjiao5082 2019-07-13 06:14
浏览 102
已采纳

如何从特定行PHP的sum(columns)函数中获取值

I'm trying to pull values from two columns based from an id. I have the following data in MySQL:

id | Rental | Rentals_Out
 1     11         11

I want to add both of those two columns in id 1. I've tried searching here and Google, but I haven't quite found what I'm looking for.

Below is the code I'm using

$sum_column = DB::select("SELECT SUM(Rental + Rentals_Out) as total_gowns FROM tbl_products WHERE id = '1'");

Or I don't mind using Eloquent but how do I enter multiple columns under pluck function? It seems to only work for one column, and I don't want to duplicate the code.

$sum_column = UCPost::where('id', 1)->pluck('Rental')->sum();

The code works under the raw SQL statement, but the output comes out as the following:

[{"total_gowns ":"22"}]

How do I get just the value i.e. 22?

  • 写回答

1条回答 默认 最新

  • doushi4956 2019-07-13 06:21
    关注

    You can try this:

    DB::table('tbl_products')
       ->select(DB::raw('Rental + Rentals_Out as total_gowns'))
       ->where('id', 1)
       ->first()->total_gowns;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题