Laravel:迁移文件只在迁移和回滚之间运行一次吗



在Laravel项目中,我在创建表迁移文件中写了以下up((:

public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}

并运行迁移命令:

php artisan migrate

并且表创建成功,然后我创建了另一个迁移文件来修改我的表,添加了一个新列,并写了以下up((:

public function up()
{
Schema::table('employees', function (Blueprint $table) {
$table->string('name');
});
}

并且如预期的那样,成功地添加了该列。

我的问题是当我修改最后一个文件以添加新列时

public function up()
{
Schema::table('employees', function (Blueprint $table) {
$table->string('name');
$table->string('address');
});
}

和运行:

php artisan migrate

该命令没有给我任何要迁移的东西,所以我应该为每次修改创建一个新的迁移文件,还是应该运行命令之一

php artisan migrate:rollback

php artisan migrate:refresh

得到我的修改?但在最后的命令中,数据会丢失,我不希望发生这种情况。

这个答案有两部分。

只要您还在开发中:是的,您可以随意编辑迁移并来回滚动,直到您对结果感到满意。

一旦在其他地方(如生产系统(执行了迁移:您就不应该再更改迁移。这里的重点是要有一个机制,可以回放结构中的变化。Laravel使用了一个非常简单的"我已经运行了这个迁移吗?"功能来查看它还需要为该数据库运行迁移的哪些部分。因此,以后再也不会进行同样的迁移了。

TL;DR:对于您的问题

我应该为每个修改创建一个新的迁移文件吗

人们可以说:是的!

正如ArSen所说,只要仍在开发中,您就可以修改migration文件,例如将它们组合在一个文件中,如

public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('address');
$table->timestamps();
});
}

然后从Laravel Docs 在您的终端中运行

php artisan migrate:fresh

当您在本地开发时,更新"迁移文件"是正常的。每次更新后,你必须做第一件或第二件事:

run php artisan migrate:rollback --step=1 WITH OLD VERSION of migration file, after 
that change migration file as you wish and run "php artisan migrate" again

manually delete record from migrations table, and manually delete all changes that 
migration produced (e.g. delete db table) and after that just run "php artisan migrate"

最新更新