dongxiji0687 2016-01-13 22:45
浏览 85
已采纳

Laravel Eloquent created_at正在更新

I just hit a snag with Eloquent's (Laravel 5.2.10) default timestamps. By default the $table->timestamps() method gives you a created_at and an updated_at column in your table which are updated accordingly.

However, when I was trying some test entries, I noticed that when you update a record, the updated_at field gets updated, as it should, but the created_at field also gets updated: its hours stays at the created time, but the minutes and seconds get updated to match the updated_at field.

If that was too wordy, here is an example:

+---------------------+---------------------+
| created_at          | updated_at          |
+---------------------+---------------------+
| 2016-01-13 17:13:27 | 2016-01-13 22:13:27 |
| 2016-01-13 16:14:41 | 2016-01-13 21:14:41 |
+---------------------+---------------------+

Notice that the minutes and seconds are the exact same for the created_at and updated_at field.

I tried to look through the Model class where the timestamps are set, but it turns out the setCreatedAt() method is indeed not called when just updating a record.

Why does this happen?
How do I prevent the created_at field from changing? (more important)

  • 写回答

1条回答 默认 最新

  • dsfh40613182 2016-01-13 22:50
    关注

    Your issue is probably related to this issue here: https://github.com/laravel/framework/issues/11518

    Long story short, many people's created_at column had the ON UPDATE CURRENT_TIMESTAMP attribute.

    As stated on the Github page:

    MySQL 5.7 no longer allows 0000-00-00 as a valid timestamp with strict mode turned on (which it is by default). So either use ->nullableTimestamps() or ->timestamp()->useCurrent().

    So, you can fix this by changing this:

    $table->timestamps();
    

    To either one of these options:

    // Option 1:
    $table->nullableTimestamps();
    
    // Option 2:
    $table->timestamp('updated_at')->useCurrent();
    $table->timestamp('created_at')->useCurrent();
    

    Also, on this MySQL page: https://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html

    Alternatively, if explicit_defaults_for_timestamp is disabled (the default), do either of the following:

    Define the column with a DEFAULT clause that specifies a constant default value.

    Specify the NULL attribute. This also causes the column to permit NULL values, which means that you cannot assign the current timestamp by setting the column to NULL. Assigning NULL sets the column to NULL.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c