[英]Can php/laravel batch update()
Supposed I'm creating a bank management system. 假设我正在创建一个银行管理系统。 I want to make some of users' account activated.
我想激活一些用户帐户。 So I can...
所以我可以
$ids = [1, 2, 3];
User::where(function($enq) use($ids) {
foreach ($ids as $id)
$enq->orwhere('id', $id);
})->update(['activated'=>true]);
But how about making their money autoincrese $10 ? 但是如何使他们的钱自动增加10美元呢?
$ids = [1, 2, 3];
User::where(function($enq) use($ids) {
foreach ($ids as $id)
$enq->orwhere('id', $id);
})->update(function(){
//what should I write here??? maybe I can write
//$this_obj->money+=10;
});
The biggest problem is that, I can't get the "current object" inside the update(). 最大的问题是,我无法在update()中获得“当前对象”。 My English is not very well, I hope my description won't confused anyone.
我的英语不太好,希望我的描述不会使任何人感到困惑。 And I hope to get a good solution.
我希望得到一个好的解决方案。 Thanks!
谢谢!
The query builder includes an increment method that could handle this: 查询构建器包括一个可以处理此问题的增量方法:
User::whereIn('id', $ids)->increment('money', 10);
Note that I also used the whereIn method as a simple replacement of your loop of orwhere calls. 请注意,我还使用whereIn方法代替了您的orwhere调用循环。
Laravel Eloquent Model provides increment method for incrementing a column's value by a given amount: https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Model.php#L389 ` Laravel Eloquent模型提供了一种将列值增加给定数量的增量方法: https ://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Model.php#L389`
What you can do: 你可以做什么:
$ids = [1, 2, 3];
User::where(function($enq) use($ids) {
foreach ($ids as $id)
$enq->orwhere('id', $id);
})->increment('money', 10);
Or even better: 甚至更好:
$ids = [1, 2, 3];
User::whereIn('id', $ids)
->increment('money', 10);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.