Eloquent - Updating all models in a collection

前端 未结 2 721
自闭症患者
自闭症患者 2021-02-07 15:11

I want to set a certain attribute in all the models of a collection.

in plain SQL:

UPDATE table SET att = \'foo\' WHERE id in (1,2,3)

t

2条回答
  •  一个人的身影
    2021-02-07 15:28

    The best solution in one single query is still:

    MyModel::whereIn('id',[1,2,3])->update(['att'=>'foo']);
    

    If you already have a collection of models and you want to do a direct update you can use modelKeys() method. Consider that after making this update your $models collection remains outdated and you may need to refresh it:

    MyModel::whereIn('id', $models->modelKeys())->update(['att'=>'foo']);
    $models = MyModel::findMany($models->modelKeys());
    

    The next example I will not recommend because for every item of your $models collection a new extra query is performed:

    $models->each(function ($item) {
        $item->update(['att'=>'foo']);
    });
    

    or simpler, from Laravel 5.4 you can do $models->each->update(['att'=>'foo']);

    However, the last example (and only the last) is good when you want to trigger some model events like saving, saved, updating, updated. Other presented solutions are touching direct the database but models are not waked up.

提交回复
热议问题