Laravel 5.4:直接从数据库中的列中减去数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47431987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:59:31  来源:igfitidea点击:

Laravel 5.4: Directly Subtract number from column in database

phpmysqllaravellaravel-5.4laravel-query-builder

提问by Amit Gupta

I want to subtract 100 number from credit column in database that is having int data type. I am looking for the way to directly subtract it with some Laravel query. But right now I first get the column value from the table and then subtract and then need to write update query to update it like below:

我想从具有 int 数据类型的数据库中的 credit 列中减去 100 个数字。我正在寻找用一些 Laravel 查询直接减去它的方法。但是现在我首先从表中获取列值,然后减去,然后需要编写更新查询来更新它,如下所示:

$subtractCredit = 100;

// Get Total Credit
$totalCredit = User::select('credit')->where(['username'=>$username])-
>first(); 

// Subtract 100 from Total Credit
$totalCredit = $totalCredit->credit - $subtractCredit;

// Update Credit in Table
User::where(['username'=>$username])->update(['credit' => $totalCredit]);

In the above code, I first get total credit from query and then subtract 100 from total credit and then update credit again with update query.

在上面的代码中,我首先从查询中获得总信用,然后从总信用中减去 100,然后使用更新查询再次更新信用。

Please let me know the better approach of doing it.

请让我知道这样做的更好方法。

回答by Joel Hinz

There's a built-in function to decrement:

有一个内置的递减函数:

User::where('username', $username)->decrement('credit', 100);

Docs: https://laravel.com/docs/5.4/queries#increment-and-decrement

文档:https: //laravel.com/docs/5.4/queries#increment-and-decrement

Note that it's sugar for the update statement, so you don't need to call save()or update()afterwards.

请注意,它是更新语句的糖,因此您不需要调用save()update()之后。

回答by Sagar Gautam

You can do it with raw query like,

您可以使用原始查询来完成,例如,

User::where('username', $username)
->update(array(
    'credit' => DB::raw('credit - 100')
));

I hope you will understand.

我希望你会明白。