Laravel 架构:默认为空,更新时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42782161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:33:30  来源:igfitidea点击:

Laravel Schema: Null default, timestamp on update

phpmysqllaravel

提问by Sherwin Flight

I've just started working with Laravel so am getting used to how things are done.

我刚刚开始使用 Laravel,所以我已经习惯了工作的方式。

I've been trying to do something that I cannot seem to find an example of online. I'm using the Schema builder to create a new table.

我一直在尝试做一些我似乎无法在网上找到的例子。我正在使用架构构建器来创建一个新表。

What I want is a datetime field with the default value to be NULL, but to have "ON UPDATE CURRENT_TIMESTAMP".

我想要的是一个日期时间字段,其默认值为 NULL,但具有“ON UPDATE CURRENT_TIMESTAMP”。

I've tried a number of things, but here was my latest attempt:

我尝试了很多东西,但这是我最近的尝试:

$table->dateTime('opened_on')->default(Capsule::raw('NULL ON UPDATE CURRENT_TIMESTAMP'));

With this code I get an "Invalid default value for 'opened_on'" error.

使用此代码,我收到“'opened_on' 的默认值无效”错误。

Any feedback or suggestions would be appreciated.

任何反馈或建议将不胜感激。

回答by Alex Slipknot

I usually use this syntax for migrations:

我通常使用这种语法进行迁移:

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

回答by Aman Kumar

Use ->timestamps()in laravel

在 Laravel 中使用->timestamps()

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

Set Default null database table

设置默认空数据库表

ALTER TABLE tbl MODIFY `opened_on` DATE DEFUALT NULL;

You Have to create your database table through migration in laravel

您必须通过在 laravel 中的迁移来创建数据库表

回答by Sherwin Flight

For me it was easier to just create a datetime field set to NULL by default, and then update the timestamp in PHP rather than let MySQL do it.

对我来说,创建一个默认设置为 NULL 的日期时间字段更容易,然后在 PHP 中更新时间戳而不是让 MySQL 来做。

回答by Alexey Mezenin

Do not reinvent the wheel and use built-in Laravel functionality. Just add ->timestamps()which will create created_atand updated_atcolumns. When you'll update data using Eloquent, Laravel will set the current date and time to the updated_atcolumn. Also, updated_atwill be automatically converted to the Carbon instance.

不要重新发明轮子并使用内置的 Laravel 功能。只需添加->timestamps()这将创建created_atupdated_at列。当您使用 Eloquent 更新数据时,Laravel 会将当前日期和时间设置为该updated_at列。此外,updated_at会自动转换为 Carbon 实例。

https://laravel.com/docs/5.4/eloquent#eloquent-model-conventions(look at the Timestamps section)

https://laravel.com/docs/5.4/eloquent#eloquent-model-conventions(查看时间戳部分)