如何在 laravel eloquent 中添加两列值并执行 where 条件

Tha*_*ung 5 php laravel eloquent

这是我的桌子:

id       remaining_amount     additional_amount
1             200                   0
2             100                -100
3             300                 100
4             200                 -50
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取总和为剩余金额+额外金额> 0 的行。

$result = $this->model->where('remaining_amount' + 'total' > 0)->get();
Run Code Online (Sandbox Code Playgroud)

它不起作用。然后我尝试这样:

$result = DB::table('cash')->select(DB::raw('remaining_amount+additional_amount AS total'))
                ->where('total','>',0)
                ->get();
Run Code Online (Sandbox Code Playgroud)

它也不起作用。

请告诉我解决这个问题的方法。

Sar*_*mar 1

您不能对计算值执行 where 条件。尝试使用laravel 集合中的过滤器来获得所需的输出。

$result = DB::table('cash')
    ->select(DB::raw('(remaining_amount+additional_amount) AS total'))
    ->get();
Run Code Online (Sandbox Code Playgroud)

执行过滤器

return collect($result)->filter(function($value){
    return $value->total > 0;
})->values()->all();
Run Code Online (Sandbox Code Playgroud)