Eloquent model mass update

前端 未结 7 1660
长发绾君心
长发绾君心 2020-12-03 00:41

Please correct me if I am wrong, but I think there is no such thing as mass update in an Eloquent model.

Is there a way to make a mass update on the DB table without

7条回答
  •  [愿得一人]
    2020-12-03 01:20

    Use database transactions to update multiple entities in a bulk. Transaction will be committed when your update function finished, or rolled back if exception occurred somewhere in between.

    https://laravel.com/docs/5.4/database#database-transactions

    For example, this is how I regenerate materialized path slugs (https://communities.bmc.com/docs/DOC-9902) for articles in a single bulk update:

    public function regenerateDescendantsSlugs(Model $parent, $old_parent_slug)
        {
            $children = $parent->where('full_slug', 'like', "%/$old_parent_slug/%")->get();
    
            \DB::transaction(function () use ($children, $parent, $old_parent_slug) {
                /** @var Model $child */
                foreach ($children as $child) {
                    $new_full_slug  = $this->regenerateSlug($parent, $child);
                    $new_full_title = $this->regenerateTitle($parent, $child);
    
                    \DB::table($parent->getTable())
                        ->where('full_slug', '=', $child->full_slug)
                        ->update([
                            'full_slug' => $new_full_slug,
                            'full_title' => $new_full_title,
                        ]);
                }
            });
        }
    

提交回复
热议问题