Laravel chunk and delete

后端 未结 4 1110
太阳男子
太阳男子 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:49

    If i understand correctly, the issue is that deleting a large amount of entries takes too much ressources. doing it one post at a time will take too long too.

    try getting the min and the max of post.id then chunk on those like

    for($i = $minId; $i <= $maxId-1000; $i+1000) {
        Post::where('arch_id', $posts_archive->id)->whereBetween('id', [$i, $i+1000])->delete();
        sleep(2);
    }
    

    customize the chunk and the sleep period as it suites your server ressources.

提交回复
热议问题