Laravel通过迁移文件创建数据表
1、创建test数据表的迁移文件
php artisan make:migration create_test_table
创建成功
在这里插入图片描述
创建成功后会在database文件夹下的migrations文件夹下生成迁移文件
在这里插入图片描述
2、编写数据段
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTestTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(‘test’, function (Blueprint $table) {
$table->bigIncrements(‘id’);
$table->string(‘name’,255);
$table->string(‘password’,255);
$table->float(‘price’,8,2);
$table->integer(‘phone’);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists(‘test’);
}
}
执行所有未执行过的迁移文件
php artisan migrate
执行指定的迁移文件
php artisan migrate –path=/database/migrations/2022_04_05_130612_create_test_table.php
在这里插入图片描述
第一次执行artisan migrate命令创建数据表的时候除了生成迁移文件指定的数据表还会生成一个migrations记录表,被执行过的迁移文件都会被记录在这个表中,下次再执行artisan命令创建数据表的时候是不会执行被记录在migrations数据表的迁移文件的,如果需要重新执行迁移文件,需要进行回滚迁移操作
在这里插入图片描述
3、回滚迁移
当我们刚刚创建一张表却发现少了几个字段需要重新建表,这时候需要先进行回滚迁移删除刚刚创建的表才可以再次运行迁移命令
要回滚到最后一次操作,你可以用下 rollback 命令。此命令会回滚到最后一批的迁移,这可能会包含多个迁移文件:
php artisan migrate:rollback
通过向 rollback 命令加上 step 参数,可以回滚指定数量的迁移。例如,以下命令将回滚最后五个迁移
php artisan migrate:rollback –step=5
回滚应用程序所有的迁移:
php artisan migrate:reset
发表评论