【问题标题】:Laravel - Arithmetical operationLaravel - 算术运算
【发布时间】:2017-10-26 14:50:10
【问题描述】:

我正在尝试计算两列值,但收到以下错误。发票和付款之间的减号是算术运算。你能帮帮我吗?

Controller.php

public function getIndex( Request $request )
{
$this->data['balanceTotal'] = \DB::table('tb_accounts')->select('sum(invoice-payment)')->get();
return view('account.index',$this->data);
}

Index.blade.php

{{ $balanceTotal }}

错误

SQLSTATE[42S22]:未找到列:1054 未知列 “字段列表”中的“总和(发票付款)”(SQL:选择 sum(invoice-payment) 来自tb_accounts)

【问题讨论】:

  • DB 表中是否有发票付款列?
  • @NipunTyagi 我有发票和付款栏。不是发票付款栏
  • 看我的回答。我根据你的 cmets 更新了这个

标签: php laravel


【解决方案1】:

你需要一个原始表达式:

\DB::table('tb_accounts')->select(\DB::raw('sum(invoice)'))

但是,我想您需要将 invoicepayment 相加:

\DB::table('tb_accounts')->select(\DB::raw('(invoice - payment) AS amount'))

查看文档:https://laravel.com/docs/5.5/queries#raw-expressions

注意:避免在列名中使用 minus 或使用反引号 (Do minus sign in mysql table column names cause issues?)

【讨论】:

  • 嗨。现在它说 Class 'App\Http\Controllers\DB' not found
  • 我用作\DB::table('tb_accounts')->select(DB::raw('(invoice - payment) AS amount')))
  • 如果您使用 DB 门面超过 1 次,最好导入命名空间:use DB;
  • 使用 Illuminate\Support\Facades\DB;或使用数据库; ??
  • 两者都是可能的 ;-)
【解决方案2】:

这会解决你的问题

use Illuminate\Support\Facades\DB;
DB::table('tb_accounts')->select(\DB::raw('(invoice + payment) AS amount'))

您收到此错误 htmlentities() expects parameter 1 to be string, array given (View: /home/unive/public_html/sistem/resources/views/accounts/inde‌​x.blade.php)

因为如果您需要在视图中传递数组,您将传递数组代替字符串,请尝试像这样返回

return view('account.index')->withdata($data);

然后在你的index.blade.php中使用

$data['balanceTotal'];

【讨论】:

    猜你喜欢
    • 2016-03-10
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2012-12-16
    • 2022-01-07
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    相关资源
    最近更新 更多