我想使用Laravel Schema Builder/Migrations创建一个默认值为CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP的时间戳列。我已经多次阅读Laravel文档,我不知道如何将其作为时间戳列的默认值。

timestamps()函数将它所生成的两列的默认值设置为0000-00-00 00:00。


当前回答

使用保罗·弗雷塔斯的建议。


在Laravel修复此问题之前,您可以在Schema::create运行之后运行标准数据库查询。

    Schema::create("users", function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('given_name', 100);
        $table->string('family_name', 100);
        $table->timestamp('joined');
        $table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
        $table->string('timezone', 30)->default('UTC');
        $table->text('about');
    });
    DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");

它对我产生了奇效。

其他回答

唯一对我有用的是

DB::statement("ALTER TABLE orders CHANGE updated_at updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");

使用保罗·弗雷塔斯的建议。


在Laravel修复此问题之前,您可以在Schema::create运行之后运行标准数据库查询。

    Schema::create("users", function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('given_name', 100);
        $table->string('family_name', 100);
        $table->timestamp('joined');
        $table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
        $table->string('timezone', 30)->default('UTC');
        $table->text('about');
    });
    DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");

它对我产生了奇效。

它将100%工作。通过这种方式,您可以在更改列的datetype后设置默认的datetime值。

Schema::table('table_name', function (Blueprint $table) {
            $table->dateTime('ans_time')->default(now())->change();
        });

在Laravel 5中:

$table->timestamps(); //Adds created_at and updated_at columns.

文档:http://laravel.com/docs/5.1/migrations creating-columns

创建created_at和updated_at列:

$t->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$t->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));

你需要MySQL版本>= 5.6.5有多个列的CURRENT_TIMESTAMP