如何修改时间戳列?

How to modify a timestamp column?

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

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

遇到这种情况你会怎么做? 提前致谢

您尝试的另一种方法是手动添加 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'];
}

我认为您应该阅读 DATETIMETIMESTAMP:

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

Range - 日期时间数据类型支持日期和时间在 1000-01-01 00:00:00 和 9999-12-31 [=54= 之间的范围内].但时间戳数据类型支持日期和时间范围在“1970-01-01 00:00:01”到“2038-01-19 08:44:07”之间。

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

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

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

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

因此您不能存储日期时间值:'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');
        });
    }

在此处阅读更多内容:What is the difference between MySQL DATETIME and TIMESTAMP data type?