Laravel 5.3+ 自动添加创建时间与更新时间详解

版权声明:尊重原创喔,转载请注明 https://blog.csdn.net/lgyaxx/article/details/79374471

本文已经迁移至我的个人技术博客:

Laravel 5.3+ 自动添加创建时间(created_at)与更新时间(updated_at)详解


注意:文章内容建立在Migrations之上,如果你对Migration不熟悉,可以先参考 Laravel数据库迁移(Database Migration)操作实例

Laravel 5.3之前,migrations中的$table->timestamps()所创建的created_atupdated_at两个column都是不允许为空的,而在5.3开始,官方文档中写道:

Command Description
$table->timestamps(); Adds nullable created_at and updated_at columns.

我们可以看到,现在这两个column都可以为NULL

如果我们保留默认的migration,那么在更新及插入数据时,Laravel会自动帮我们处理好created_atupdated_at两个时间戳,即插入数据时,两者都被更新为服务器当前时间,更新数据时,updated_at被更新为操作发生时间。

但是如果我们后端代码没有使用Laravel,例如我们需要使用Python来插入一部分数据,那么我们有两种选择:

  1. 手动生成时间并插入
  2. migration文件中,调整created_atupdated_at的类型

第一种显而易见,那么我们就不多说。
第二种方法,我们将原有的$table->timestamps()去掉,然后添加上以下代码:

use Illuminate\Support\Facades\DB;

...

    public function up()
    {
	    ...
		$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
		$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
		...
	}
...

注意,我们需要引入DB Facade来使用DB::raw语句。那么我们看到,现在created_at以及updated_at两个column被分别用timestamp()进行声明,我们看一下官方文档怎么写的:

Command Description
$table->timestamp(‘added_on’); TIMESTAMP equivalent for the database.

可以看到,使用timestamp()声明的column不能为NULL

那么我们需要添加两个column的默认值:

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

这样一来,我们在未使用Laravel而需要操作数据库时,不需要主动插入时间,数据库也会帮我们自动插入及更新时间戳。

猜你喜欢

转载自blog.csdn.net/lgyaxx/article/details/79374471