laravel运用Migrate进行建表

本文介绍了如何在Laravel中使用Migrate创建表,并着重讲解了如何设置`created_at`和`updated_at`字段自动更新时间。在Laravel 5.3之后,默认时间会是null,需要手动设置。通过`DB::raw()`函数,可以实现创建时间和更新时间的自动填充。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

建立一个migrate

php artisan make:migration create_table_anke 

编写migrate建表

Schema::create('anke', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name', 20);
    $table->timestamps();
});

表生成器包含一系列的字段类型用于构建表:

命令描述
$table->bigIncrements('id');Incrementing ID using a "big integer" equivalent.
$table->bigInteger('votes');BIGINT equivalent to the table
$table->binary('data');BLOB equivalent to the table
$table->boolean('confirmed');BOOLEAN equivalent to the table
$table->date('created_at');DATE equivalent to the table
$table->dateTime('created_at');DATETIME equivalent to the table
$table->decimal('amount', 5, 2);DECIMAL equivalent with a precision and scale
$table->double('column', 15, 8);DOUBLE equivalent with precision
$table->enum('choices', array('foo', 'bar'));ENUM equivalent to the table
$table->float('amount');FLOAT equivalent to the table
$table->increments('id');Incrementing ID to the table (primary key).
$table->integer('votes');INTEGER equivalent to the table
$table->longText('description');LONGTEXT equivalent to the table
$table->mediumText('description');MEDIUMTEXT equivalent to the table
$table->morphs('taggable');Adds INTEGER taggable_id and STRING taggable_type
$table->smallInteger('votes');SMALLINT equivalent to the table
$table->softDeletes();Adds deleted_at column for soft deletes
$table->string('email');VARCHAR equivalent column
$table->string('name', 100);VARCHAR equivalent with a length
$table->text('description');TEXT equivalent to the table
$table->time('sunrise');TIME equivalent to the table
$table->timestamp('added_on');TIMESTAMP equivalent to the table
$table->timestamps();Adds created_at and updated_at columns
->nullable()Designate that the column allows NULL values
->default($value)Declare a default value for a column
->unsigned()Set INTEGER to UNSIGNED

更多请看https://blog.csdn.net/kjw001122/article/details/79908419


我们在以上运用 $table->timestamps(); 生成添加时间及修改时间,但是这个时间自Laravel 5.3后时间默认为null  ,在操作时需要自己手动添加时间

如果想要在migrate中设置时间为自动更新 需要进行已下操作
use Illuminate\Support\Facades\DB;
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值