douhuangjian9627 2019-05-16 08:32
浏览 737

在Laravel Eloquent中自动更新日期时间字段的首选方法是什么

I have a table with 3 datetime fields: 1.created_at (generated and handled by Laravel), 2.updated_at (generated and handled by Laravel), 3.custom_date (created by mine, it will be changed every time created_at or updated_at is changed).

I would that every time that a new record is created or the first two fields are changed, the custom_date is updated using a callback. How can achieve this using Eloquent in Laravel 5.7?

I have already tried using a mutator but I would avoid it because I would update the field every time created_at or updated_at are changed.

  • 写回答

1条回答 默认 最新

  • donglin9068 2019-05-17 00:48
    关注

    You should have made the configuration on your migration file like so:

    $table->timestamp('custom_date')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
    

    This way, the custom_date field will update:

    1.) When the row was created together with created_at field (on you laravel app).

    2.) When the row was updated together with updated_at field (on you laravel app).

    3.) When you made any modification directly to the database.

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入