How can I set the default value of a timestamp col

2019-01-10 02:11发布

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.

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

8条回答
乱世女痞
2楼-- · 2019-01-10 02:38

This doesn't work for a fact:

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

It doesn't remove the 'default 0' that seems to come with selecting timestamp and it just appends the custom default. But we kind of need it without the quotes. Not everything that manipulates a DB is coming from Laravel4. That's his point. He wants custom defaults on certain columns like:

$table->timestamps()->default('CURRENT_TIMESTAMP');

I don't think it's possible with Laravel. I've been searching for an hour now to see whether it's possible.


Update: Paulos Freita's answer shows that it is possible, but the syntax isn't straightforward.

查看更多
看我几分像从前
3楼-- · 2019-01-10 02:41

This is how you do it, I have checked it and it works on my Laravel 4.2.

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

Hope this helps.

查看更多
登录 后发表回答