laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Mass update without touching updated_at timestamp #2512

Open Braunson opened 3 years ago

Braunson commented 3 years ago

Looking to make a mass update on a model for a new flag I'm adding to the table but don't want to touch the updated_at timestamp. I recall long ago (5.8?) the update method supported a second parameter that one could pass an array such as ['timestamps' => false] to to avoid touching the timestamps.

It could look something like a new method updateNoTouch() or even checking for timestamps value in the $values array and if false then to not call $this->addUpdatedAtColumn($values).

A workaround currently is to just call Model::toBase()->update(['foo' => 'bar'])

mesiarm commented 3 years ago

You can also set $timestamps property in Model to false: https://laravel.com/docs/8.x/eloquent#timestamps

Braunson commented 3 years ago

@mesiarm Yes I am aware of that but this isn't permanent, I still want timestamps, just not certain times (such as a migration) when mass updating.

mesiarm commented 3 years ago

You can also disable it only in certain times as folows:

$object->timestamps = false;
$object->save();

https://stackoverflow.com/a/26689939/5135006

Braunson commented 3 years ago

@mesiarm Yes but in the case of mass updates this is not an option. e.g

Article::update([
  'foo' => 'bar'
]);
Sladewill commented 3 years ago

Just use a DB call then and don't use Eloquent

JoaoHamerski commented 3 years ago

@Sladewill Using DB isn't cleaner because it doesnt return the records, only the number of affected rows, plus you have to specify the table too. A simple option to specify that we want to do a silent update would be good.

Currently i have this code:

DB::table('simulations')
    ->where('id', $simulation->id)
    ->update(['is_sample' => ! $simulation->is_sample]);

would be better if i could do the same like this:

$simulation->silentUpdate(
    ['is_sample' => ! $simulation->is_sample]
);