PDOException:SQLSTATE [22007]:1292 UTC ISO-8601 上的日期时间值不正确

PDOException: SQLSTATE[22007]: 1292 Incorrect datetime value on UTC ISO-8601

您好,我收到以下错误

PDOException: SQLSTATE[22007]: 1292 Incorrect datetime value '2022-03-07T18:08:12.000000Z' for column 'created_timestamp' at row 1 in /[path]/[to]/[project]/vendor/laravel/framework.src.Illuminate/Database/Connection.php:496

对我来说,这看起来像是有效的 UTC ISO-8601 日期格式。在下面的代码中

    // migration
    Schema::create('my_model', function (Blueprint $table) {
      // ...
      $table->datetime('created_timestamp');
    });
    // model
    class MyModel extends Model
    {
      protected $casts = [
        'created_timestamp' => 'datetime',
      ];
    }
    // code
    var_dump($instance->getAttribute('created_timestamp'));
    DB::table($model->getTable())->upsert(
      [$instance->toArray()],
      [$model->getKeyName()]
    );

var dump 打印了一个 carbon 实例。文档说:

When a column is cast as a date, you may set the corresponding model attribute value to a UNIX timestamp, date string (Y-m-d), date-time string, or a DateTime / Carbon instance. The date's value will be correctly converted and stored in your database.

此处的文档 https://laravel.com/docs/8.x/eloquent-mutators#date-casting-and-timezones 也强烈建议保留默认的 UTC 格式,这样我就不想转换为自定义格式 'datetime:Y-m-d H:i:s'。

为什么我不能更新这个模型?

关键是用 $instance->getAttributes() 替换 $instance->toArray() 以获得 MySQL 友好值 w/o 自定义转换