如何在迁移 laravel 中使用 alter table 添加字段?

How can I add field using alter table on the migration laravel?

我用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');
    }     
}

我想像这样添加新字段:

$table->string('mobile_number',20)->nullable();

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

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

所以如果我使用 alter table,它会自动迁移。所以如果代码合并到 development 或 master

,数据库中的 table 将自动添加 mobile_number 字段

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

如何使用 alter table 添加字段?

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

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

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

DB::statement("ALTER TABLE users .....");

然而,如果你能让它工作,模式方式会更好

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

php artisan make:migration add_mobile_number_to_users_table --table=users

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

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