Eloquent update method change created_at timestamp

核能气质少年 提交于 2019-12-23 16:09:49

问题


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_at when record is updated
  • you might have registered some events that change created_at when record is updated
  • make sure your created_at field in posts table in database is not defined as CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP - this way whenever you update record, created_at will 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!