【问题标题】:Laravel 6 - Updating the model timestampsLaravel 6 - 更新模型时间戳
【发布时间】:2020-01-02 17:34:48
【问题描述】:

在我的 Laravel 6 应用程序内部执行一些操作后,我正在尝试更新我的模型对象 $last(CurrentConditions 类)。正如您在下面看到的,我正在尝试将update_time 属性更新为当前时间戳。除了这个属性,我在 CurrentConditions 模型中有另一个时间戳属性:external_update_time,我希望这个属性在更新和保存 $last 对象后保持不变。问题是external_update_time 属性在保存模型后更新为当前时间。

/** @var CurrentConditions $last */
$last = $this->getLastUpdatedCurrentConditions($cityID);
$last->update_time = Carbon::now("UTC");
$last->save();

这是我的模型:

class CurrentConditions extends Model
{
    protected $table = 'current_conditions';

    ...

    public $timestamps = false;

    protected $dates = ['update_time', 'external_update_time'];

    ...
}

这是我的迁移代码:

Schema::create("current_conditions", function (Blueprint $table) {
      $table->bigIncrements("current_conditions_id");
      ...
      $table->timestamp("external_update_time");
      $table->timestamp("update_time")->useCurrent();
});

那么为什么external_update_time 也会更新呢?感谢您的帮助。

【问题讨论】:

  • 您是如何在架构中定义这些字段的,迁移?
  • @lagbox 好点。我更新了问题。
  • 这不是mysql吗?
  • @lagbox 是的,MariaDB 10.1。
  • 这能回答你的问题吗? Laravel Timestamp Being Updated Without Explicit Call To Do So 前段时间我也遇到过同样的问题,当您的迁移中有一个不可为空的时间戳时就会发生这种情况;所述列的第一个实例将具有意外的默认更新值。

标签: mysql laravel eloquent laravel-6 mysql-5.7


【解决方案1】:

请检查是否在更新时未设置 external_update_time 以设置 CurrentTimeStamp

在模式表设计中

【讨论】:

    【解决方案2】:

    这就是 MySQL 5.7 的工作方式 - 第一个时间戳将使用当前时间戳进行更新。您应该修改迁移中列的顺序(假设它尚未部署到实时服务器)以实现您想要的:

    $table->timestamp("update_time")->useCurrent();
    $table->timestamp("external_update_time");
    

    【讨论】:

      猜你喜欢
      • 2014-05-21
      • 2017-06-06
      • 2015-08-30
      • 1970-01-01
      • 2018-12-27
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      相关资源
      最近更新 更多