【问题标题】:How to get the value from sum(columns) function for a specific row PHP如何从特定行 PHP 的 sum(columns) 函数中获取值
【发布时间】:2019-11-22 19:02:44
【问题描述】:

我正在尝试从基于 id 的两列中提取值。我在 MySQL 中有以下数据:

id | Rental | Rentals_Out
 1     11         11

我想将这两列都添加到 id 1 中。我已尝试在此处和 Google 中搜索,但还没有完全找到我要查找的内容。

下面是我正在使用的代码

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

或者我不介意使用 Eloquent 但如何在 pluck 函数下输入多个列?它似乎只适用于一列,我不想重复代码。

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

代码在原始 SQL 语句下运行,但输出如下:

[{"total_gowns ":"22"}]

我如何只获得值,即 22?

【问题讨论】:

  • 去掉SUM这个词

标签: php mysql laravel model controller


【解决方案1】:

你可以试试这个:

DB::table('tbl_products')
   ->select(DB::raw('Rental + Rentals_Out as total_gowns'))
   ->where('id', 1)
   ->first()->total_gowns;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多