简体   繁体   中英

How can I alter a column to be “not null” in Laravel 5?

Here's some sample code:

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

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

The first part works great. Basically, I'm taking an existing user_id column and altering it so that it's nullable. Works perfectly.

However, when I run migrate:rollback, the column stays nullable and I have an imperfect up/down migration relationship. What's the best practice solution for resolving this?

The only way I would suggest doing this is to run the DB::statement() method. Something like the following

public function down() {
    DB::statement('ALTER TABLE `orders` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}

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