How to add two columns value and perform where con

2019-07-31 08:44发布

This is my table:

id       remaining_amount     additional_amount
1             200                   0
2             100                -100
3             300                 100
4             200                 -50

I'm trying to get the rows which have a sum of remaining_amount + additional_amount > 0 .

$result = $this->model->where('remaining_amount' + 'total' > 0)->get();

it didn't work. Then I tried like this:

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

It doesn't work either.

Please show me the way to solve this.

4条回答
Lonely孤独者°
2楼-- · 2019-07-31 08:53

Try this using whereRaw:

$query = DB::table('cash')
    ->whereRaw("(remaining_amount+additional_amount AS total) > 0)")
    ->get();
查看更多
beautiful°
3楼-- · 2019-07-31 09:01

You can not perform where condition on calculated value. Try using filter from laravel collection to get the desired output.

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

Performing filter

return collect($result)->filter(function($value){
    return $value->total > 0;
})->values()->all();
查看更多
相关推荐>>
4楼-- · 2019-07-31 09:15
$result = DB::table('cash')->get();

$result = collect($result)->filter(function($value){
    return $value->remaining_amount + $value->additional_amount > 0;
    })->values()->all();

Got it. Thanks

查看更多
爷、活的狠高调
5楼-- · 2019-07-31 09:16

I think you sohuld use aggregate method to sum as

$result = DB::table('cash')->SELECT SUM(remaining_amount)+additional_amount AS total')->where('total','>',0)->get();

Hope it will work for you

查看更多
登录 后发表回答