Laravel 5.2 - 用一个查询更新多行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34885575/
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
Laravel 5.2 - Updating multiple rows with one query
提问by Bill Garrison
So I do a lot of calculations and at the end I have rates that need to be saved to existing rows in a table.
所以我做了很多计算,最后我有需要保存到表中现有行的费率。
The array I have will be similar to the following:
我拥有的数组将类似于以下内容:
[
<model_id> => [
'rate' => <some rate>
]
<model_id_2> => [
'rate' => <some other rate>
]
.....
]
Now obviously I could foreach through this array and do an update for each and every item in the array but I could end up with 100 update calls. Is there a way (through laravel's eloquent OR even a raw sql query) to do all these updates through one call?
现在显然我可以通过这个数组 foreach 并对数组中的每一项进行更新,但我最终可能会进行 100 次更新调用。有没有办法(通过 laravel 的 eloquent 或者甚至是原始 sql 查询)通过一次调用来完成所有这些更新?
采纳答案by subzeta
If you are worried about the request spent time you can handle this by firing an event and then queueing your listener/job, who will save your model, so it can be processed asynchronously. For examples, go to Laravel Docs for Queues
如果您担心请求花费的时间,您可以通过触发事件然后将您的侦听器/作业排队来处理此问题,谁将保存您的模型,以便可以异步处理它。例如,转到Laravel Docs for Queues
As long as I know you cannot update multiple rows on Laravel.
只要我知道你不能在 Laravel 上更新多行。
回答by Nikunj K.
You may try with Eloquent update()
for multiple records update. Here is some code which I am using for update multiple records into the my table.
您可以尝试使用 Eloquentupdate()
进行多条记录更新。这是我用于将多个记录更新到我的表中的一些代码。
\App\Notification::where('to_id', '=', 0)
->update(['is_read' => 1]);