Laravel:使用更新的迁移将列添加到 table

Laravel: Add column to table with updated migration

我正在尝试迁移一个迁移文件中的特定行。

示例:

之前:

Schema::create('categories', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('category_name');
  $table->integer('parent_id')->nullable();
  $table->timestamps();
});

之后:

Schema::create('categories', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('category_name');
  $table->string('img_url'); // ← new column
  $table->integer('parent_id')->nullable();
  $table->timestamps();
});

现在我只想迁移行:$table->string('img_url');

可能吗?

听起来您正在尝试向已通过迁移创建的 table 添加一列。如果是这种情况,而不是使用 Schema::create(...),您需要使用 Schema::table(...).

通常,您会为此创建一个新的迁移:

$ php artisan make:migration add_img_url_to_categories

这将在 /database/migrations 处创建一个名为 2019_10_21_165554_add_img_url_to_categories.php 的新文件。然后将此代码添加到 up() 函数中:

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

您的另一个选择是完全按照您所做的那样编辑迁移(根据您问题中的代码),然后 运行:

$ php artisan migrate:fresh // drop all tables and re-run all migrations

$ php artisan migrate:refresh // reset and re-run all migrations

但请记住,这些都是破坏性操作 – 这意味着您将丢失数据库中已有的所有数据。在早期开发中,这可能无关紧要。但是您真的应该养成为数据库更改创建 new 迁移的习惯,而不是编辑现有的迁移。

迁移的目的是让您(或任何使用您的应用程序的人)可以快速部署与您的应用程序期望的架构相匹配的数据库。 在开发过程中,在调整数据库模式以适应正在开发的功能时编辑迁移并不罕见。

但是,一旦您部署或发布了您的应用程序,您应该将所有迁移视为锁定或只读。从那时起的任何数据库更改都应在 new 迁移中完成。