Home > OS >  Updating multiple entities in Laravel
Updating multiple entities in Laravel

Time:11-05

Laravel version in composer.json: "laravel/framework": "^8.65"

I have a Laravel backend and I am trying to get all entities from a model that satisfy a condition, and then iterate through them and update some of them according to a certain logic, here's a simplified version of my code that experiences the same issue I'm having with the actual code:

$entities = SomeModel::where('field1', 1)->get();
$entities->each(function ($entity, $index) {
    $entity->update(['field2' => $index]);
});

I have 5 entities that satisfy field1 == 1 in SomeModel, so after running this code I'd expect one of them to have field2 set to 0, another one set to 1, ..., and the last one set to 4.

However, all 5 of them end up with field2 set to 4

I've tried using ->fill(['field2' => $index])->save(), I've tried using a foreach loop, but I'm still getting the same behaviour where updating an entity in the returned collection seems to update all entities from that collection

EDIT: After trying out numerous approaches I think this might have to do with the fact that this model's PK is not unique, actually the 'field1' in my snippet is what I set as PK in the model. How could I approach this considering there's no unique key in my model (the uniqueness ia a little complicated, either the combination of field1 and fieldX is unique, or the combination of field1 and fieldY, or the combination of field1 and fieldZ)

CodePudding user response:

You can use Query Builder like this:

DB::table('some_table')->where('field1', 1)->update([
    'some_field' => 'New value'
]);

See here: https://laravel.com/docs/10.x/queries#update-statements

CodePudding user response:

In Laravel , with his amazing ORM eloquent , you can easily get all entities from a model that satisfy a condition and then iterate through them and update some of them just by doing that :

( in this example, I want to select all the entities concerned and delete them )

Model::where('field', value)->get()->map(
   function ($entity) {
     $entity->fill(['is_deleted' => true, 'deleted_at' => date('Y-m-d H:i:s')])->save();
   }
)
  • Related