如何修改时间戳列?



我收到了现有数据库的 SQL 转储文件 有一个表,其中date_from和date_to列,它们都是时间戳类型 但date_to列的默认值为"0000-00-00 00:00:00"。 尝试将软删除添加到此表时,如下所示:

Schema::table('gamesessions', function (Blueprint $table) {
$table->softDeletes();
});

我收到以下错误:无效的日期时间格式:1292 列.的日期时间值不正确:"0000-00-00 00:00:00"。date_to

所以我试图使date_to列为空,如下所示:

Schema::table('gamesessions', function (Blueprint $table) {
$table->timestamp('date_to')->nullable()->change();
$table->softDeletes();
});

但根据Laravel文档,时间戳列是不可修改的:https://laravel.com/docs/7.x/migrations#modifying-columns

在这种情况下,你会怎么做? 提前致谢

我认为你应该阅读DATETIMETIMESTAMP的信息:

这两种数据类型都以"YYYY-MM-DD HH:MM:SS"格式存储数据,并包括日期和时间。尽管有这些相似之处,但它们仍有以下差异——

范围 − 日期时间数据类型支持介于 1000-01-01 00:00:00 和 9999-12-31 23:59:59 之间的日期和时间。但时间戳数据类型支持介于"1970-01-01 00:00:01"到"2038-01-19 08:44:07"之间的日期和时间。

大小− 日期时间需要 5 个字节以及 3 个额外的字节,用于秒的小数部分数据存储。另一方面,时间戳数据类型需要 4 个字节以及 3 个额外的字节用于小数秒的数据存储。但在MySQL 5.6.4之前,DateTime需要8个字节以及3个额外的字节用于小数秒的数据存储。

从一个时区到另一个时区的转换- 实际上在MySQL5+中,时间戳值从当前时间转换为UTC,反之亦然,而日期时间不进行任何转换。

索引 − 可以对时间戳数据进行索引,但不能对日期时间数据进行索引

查询缓存− 可以缓存具有时间戳数据类型的查询,但不能缓存具有日期时间数据类型的查询。

因此,您不能存储日期时间值:"0000-00-00 00:00:00"列date_to

change()方法允许您修改现有列的type and attributes而不修改value

尝试删除时间戳列,然后将其重新添加为可为空的时间戳列:

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('gamesessions', function (Blueprint $table) {
$table->dropColumn('date_to');
});
Schema::table('gamesessions', function (Blueprint $table) {
$table->timestamp('date_to')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('gamesessions', function (Blueprint $table) {
$table->dropColumn('date_to');
});
Schema::table('gamesessions', function (Blueprint $table) {
$table->timestamp('date_to');
});
}

在这里阅读更多:MySQL DATETIME和TIMESTAMP数据类型有什么区别?

您尝试的另一种方法是手动添加deleted_at列,如下所示:

Schema::table('gamesessions', function (Blueprint $table) {
$table->timestamp('deleted_at')->nullable();
});

游戏会话模型中

class Gamesession extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
}

最新更新