如何通过Laravel迁移将时间戳列的默认值设置为当前时间戳? [英] How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

查看:281
本文介绍了如何通过Laravel迁移将时间戳列的默认值设置为当前时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Laravel Schema Builder/Migrations创建一个默认值为CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP的时间戳列.我已经多次浏览过Laravel文档,但没有看到如何将它作为timestamp列的默认值.

I would like to make a timestamp column with a default value of CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP using the Laravel Schema Builder/Migrations. I have gone through the Laravel documentation several times, and I don't see how I can make that the default for a timestamp column.

timestamps()函数将其创建的两列设置为默认值0000-00-00 00:00.

The timestamps() function makes the defaults 0000-00-00 00:00 for both columns that it makes.

推荐答案

鉴于这是一个原始表达式,您应使用DB::raw()CURRENT_TIMESTAMP设置为列的默认值:

Given it's a raw expression, you should use DB::raw() to set CURRENT_TIMESTAMP as a default value for a column:

$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));

这在每个数据库驱动程序上都可以正常工作.

This works flawlessly on every database driver.

新快捷方式

从Laravel 5.1.25开始(请参见 PR 10962

As of Laravel 5.1.25 (see PR 10962 and commit 15c487fe) you can use the new useCurrent() column modifier method to set the CURRENT_TIMESTAMP as a default value for a column:

$table->timestamp('created_at')->useCurrent();

回到问题所在,在MySQL上,您还可以通过DB::raw()使用ON UPDATE子句:

Back to the question, on MySQL you could also use the ON UPDATE clause through DB::raw():

$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

陷阱

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆