我想使用Laravel Schema Builder/Migrations创建一个默认值为CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP的时间戳列。我已经多次阅读Laravel文档,我不知道如何将其作为时间戳列的默认值。
timestamps()函数将它所生成的两列的默认值设置为0000-00-00 00:00。
我想使用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");
它对我产生了奇效。
其他回答
使用保罗·弗雷塔斯的建议。
在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");
它对我产生了奇效。
如果你想为一个datetime列设置当前的日期时间(就像我在谷歌搜索时那样),使用这种方式
$table->dateTime('signed_when')->useCurrent();
创建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
在Laravel 5中:
$table->timestamps(); //Adds created_at and updated_at columns.
文档:http://laravel.com/docs/5.1/migrations creating-columns
从Laravel 5.1.26开始,标签为2015-12-02,添加了useCurrent()修饰符:
Schema::table('users', function ($table) {
$table->timestamp('created')->useCurrent();
});
PR 10962(随后是commit 15c487fe)导致了这一添加。
您可能还想阅读感兴趣的第3602和11518期。
基本上,MySQL 5.7(默认配置)要求您为时间字段定义一个默认值或可空值。