简体   繁体   中英

Laravel: Add column to table with updated migration

I'm trying to migrate a specific line in one migration file.

Example:

Before:

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

After:

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();
});

And now I just want to migrate the line: $table->string('img_url');

Is it possible?

It sounds like you are trying to add a column to a table that has already been created via migration. If that is the case, rather than using Schema::create(...) , you need to use Schema::table(...) .

Typically, you would create a new migration for this:

$ php artisan make:migration add_img_url_to_categories

Which will create a new file at /database/migrations called something like 2019_10_21_165554_add_img_url_to_categories.php . Then add this code to the up() function:

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

Another option you have is to edit the migration exactly as you have done (per the code in your question), and then run:

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

or

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

But keep in mind that these are both destructive operations – meaning you will lose any data you already have in your database. In early development, that might not matter. But you should really establish the habit of creating new migrations for database changes, rather than editing existing migrations.

The purpose of migrations is so that you (or anyone using your app) can quickly deploy a database that matches the schema your app is expecting. During development, it is not uncommon to edit your migrations as you tweak your database schema to accommodate the features you are developing.

However, once you have deployed or published your app, you should consider all of the migrations to be locked or read-only. Any database changes from that point should be done in a new migration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM