如何在迁移 Laravel 上使用更改表添加字段?

Suc*_*Man 3 migration laravel laravel-5 laravel-5.3

我使用 Laravel 5.3

我的迁移是这样的:

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('api_token')->nullable();
            $table->string('email',100)->unique();
            $table->string('password')->nullable();
            $table->string('avatar',100)->nullable();
            $table->string('full_name',100)->nullable();
            $table->date('birth_date')->nullable();
            $table->smallInteger('gender')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });
    }
    public function down()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        Schema::dropIfExists('users');
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }     
}
Run Code Online (Sandbox Code Playgroud)

我想添加这样的新字段:

$table->string('mobile_number',20)->nullable();
Run Code Online (Sandbox Code Playgroud)

但我不想将它添加到架构中。我想使用alter table

在我的临时服务器和实时服务器上设置了自动迁移

所以如果我使用alter table,它会自动迁移。所以如果代码合并到 development 或 master 数据库中的表会自动添加 mobile_number 字段

如果我添加架构,它不会自动迁移

如何使用alter table添加字段?

Chr*_*ips 8

您可以使用架构来更新现有表。使用 artisan 命令创建一个新的迁移,然后添加类似

Schema::table('users', function (Blueprint $table) {
    $table->string('mobile_number',20)->nullable();
});
Run Code Online (Sandbox Code Playgroud)

如果你真的想做 RAW sql 你可以做类似的事情

DB::statement("ALTER TABLE users .....");
Run Code Online (Sandbox Code Playgroud)

但是,如果您可以使其工作,模式方式会好得多


spi*_*rit 7

在命令行中,执行 artisan 命令为您的表添加新的迁移:

php artisan make:migration add_mobile_number_to_users_table --table=users
Run Code Online (Sandbox Code Playgroud)

然后你可以把你的代码放在新创建的迁移文件中:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('mobile_number',20)->nullable();
    }
}

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('mobile_number');
    }
}
Run Code Online (Sandbox Code Playgroud)