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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度