我用unsigned user_id创建了一个迁移。我如何编辑user_id在一个新的迁移,也使它为空()?

Schema::create('throttle', function(Blueprint $table)
{
    $table->increments('id');
    // this needs to also be nullable, how should the next migration be?
    $table->integer('user_id')->unsigned();
}

当前回答

试一试:

$table->integer('user_id')->unsigned()->nullable();

其他回答

安装Composer包:

composer require doctrine/dbal

在成功安装composer包后,我们可以使用迁移命令更改数据类型和更改列名。

语法:

php artisan make:migration alter_table_[table_name]_change_[column_name] --table=[table_name]

例子:

php artisan make:migration alter_table_sessions_change_user_id --table=sessions

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AlterTableSessionsChangeUserId extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('sessions', function (Blueprint $table) {
            $table->integer('user_id')->unsigned()->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('sessions', function (Blueprint $table) {
            $table->dropColumn('user_id');
        });
    }
}

然后运行:php artisan migrate

OR

或刷新表以更改列名。不使用改变方法。

Schema::create('throttle', function(Blueprint $table)
{
    $table->increments('id');
    # old code
    $table->integer('user_id')->unsigned();
    # new code
    $table->integer('user_id')->unsigned()->nullable();
}

注意:以下命令用于清除表中的数据。

php artisan migrate:refresh --path=/database/migrations/2021_09_31_050851_create_throttle_table.php

试一试:

$table->integer('user_id')->unsigned()->nullable();

我必须使用nullable(true)

Schema::table('users', function($table)
{
    $table->string('name', 50)->nullable(true)->change();
});

注意,这只在Laravel 5+中是可能的。

首先,你需要doctrine/dbal包:

composer require doctrine/dbal

现在在你的迁移中,你可以这样做,使列为空:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        // change() tells the Schema builder that we are altering a table
        $table->integer('user_id')->unsigned()->nullable()->change();
    });
}

您可能想知道如何恢复此操作。遗憾的是,不支持这种语法:

// Sadly does not work :'(
$table->integer('user_id')->unsigned()->change();

这是恢复迁移的正确语法:

$table->integer('user_id')->unsigned()->nullable(false)->change();

或者,如果你喜欢,你可以写一个原始查询:

public function down()
{
    /* Make user_id un-nullable */
    DB::statement('UPDATE `users` SET `user_id` = 0 WHERE `user_id` IS NULL;');
    DB::statement('ALTER TABLE `users` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}

再加上德米特里·切波塔列夫的回答,

如果你想一次修改多个列,你可以像下面这样做

DB::statement('
     ALTER TABLE `events` 
            MODIFY `event_date` DATE NOT NULL,
            MODIFY `event_start_time` TIME NOT NULL,
            MODIFY `event_end_time` TIME NOT NULL;
');