问题
I'm using Eloquent for database handling, when I update a record with update method created_at time stamp is changed how to prevent this from happening ?
$post = Post::update([
'name' => $name
]);
updated_at timestamp is working perfectly
回答1:
In case you don't have any custom settings in your model. You can update record like this:
$id = 5; // here put id of record you want to update
$post = Post::findOrFail($id);
$post->name = $name;
$post->save();
Using this code only name should be updated and updated_at timestamp (and not created_at). If created_at is also updated it means you might have some custom model settings or:
- you might have database triggers that change
created_atwhen record is updated - you might have registered some events that change
created_atwhen record is updated - make sure your
created_atfield inpoststable in database is not defined asCURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP- this way whenever you update record,created_atwill be also updated to current datetime
You should also make sure that you don't have for your Post model something like this:
const UPDATED_AT = 'created_at';
If would also explain why created_at is changed when you update your record.
来源:https://stackoverflow.com/questions/34479005/eloquent-update-method-change-created-at-timestamp