Laravel 7 的 ISO-8601 Timestamp 新格式与 Seeding 灌数据的问题
今天在看 L01 Section 8.4 的时候发现这么一个问题:无论怎么对'created at'
的 timeStamps
进行定义,比如$faker->dateTime()
或是Carbon::now()
,在实际灌数据的过程中,所有日期都会被转成 ISO-8601 的格式(i.e.2020-03-24T23:36:15.000000Z'
),然后报错:
$ php artisan migrate:refresh --seed
PDOException::("SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2020-03-24T23:36:15.000000Z' for column `weibo`.`users`.`email_verified_at` at row 1")
新日期序列化虽然已经在官网说明了(https://learnku.com/docs/laravel/7.x/upgrade#date-...),如果按官网的办法对 serializeDate
进行覆盖:
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
灌数据就没问题,可见数据库端还是只吃以前的日期格式(serializeDate 只处理灌数据的逻辑,但对注册和建表却完全没有操作),那问题来了,如果不改 serializeDate 同时用新日期格式的话该怎么办?目前观察:
- mysql 里
'users'
->'created at'
是TIMESTAMP
格式没错,注册了看不到毫秒; - 保险起见,建表时
timestamps()
改成timestampsTz()
,注册了还是看不到毫秒;
目测这问题可以通过魔改解决,但是我琢磨默认情况 release 出现各自为政的情况不应该啊,难道是我哪儿配置出现重大错误?
附灌数据逻辑,基本配置:UserFactory.php
...
$factory->define(User::class, function (Faker $faker) {
return [
'name' => $faker->unique()->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
'created_at' => $faker->dateTime(),
'updated_at' => $faker->dateTime(),
];
});
...
2014_10_12_000000_create_users_table.php
...
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
...
今天也遇到了这个问题,写入 MySQL 的时候报错了。 不知道不覆盖 serializeDate 的话,该怎么处理最合适。