简体   繁体   English

Laravel 5.2-使用一个查询更新多行

[英]Laravel 5.2 - Updating multiple rows with one query

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. 现在很明显,我可以遍历此数组并对数组中的每个项目进行更新,但最终可能会有100个更新调用。 Is there a way (through laravel's eloquent OR even a raw sql query) to do all these updates through one call? 有没有办法(通过laravel的雄辩甚至是原始的sql查询)通过一个调用来完成所有这些更新?

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上更新多行。

You may try with Eloquent update() for multiple records update. 您可以尝试Eloquent update()来更新多个记录。 Here is some code which I am using for update multiple records into the my table. 这是一些代码,用于将多个记录更新到我的表中。

\App\Notification::where('to_id', '=', 0)
                ->update(['is_read' => 1]); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM