Laravel chunk and delete

后端 未结 4 1171
太阳男子
太阳男子 2021-01-25 18:14

I have a large number of items (1M+) that i want to delete from a database, i fork a background job to take care of that, so that the user won\'t have to wait for it to finish t

4条回答
  •  余生分开走
    2021-01-25 18:48

    There is nothing Laravel specific about the way you'd handle this. It sounds like your database server needs review or optimization if a delete query in a job is freezing the rest of the UI.

    Retrieving each model and running a delete query individually definitely isn't a good way to optimize this as you'd be executing millions of queries. You could use a while loop with a delete limit if you wish to try to limit the load per second in your application instead of optimizing your database server to handle this query:

    do {
        $deleted = Post::where('arch_id', $posts_archive->id)->limit(1000)->delete();
        sleep(2);
    } while ($deleted > 0);
    

提交回复
热议问题