在Laravel 5迁移中使列不可为空

Jua*_*one 10 php sql laravel-5

我发现这个问题非常类似于我的Make列在Laravel迁移中不可为空,虽然它已经快3岁了,它肯定不属于Laravel 5

我的问题是我有一个迁移,它在up函数中修改了一个列使其可以为空.现在,在down函数中我想让它再次无法为空.

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

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('mytable', function(Blueprint $table) {
    /* THIS IS WHAT I WOULD EXPECT TO DO
    THOUGH OF COURSE THE FUNCTION notNullable DOES NOT WORK */
        $table->string('mycolumn')->notNullable()->change(); 
    });
}
Run Code Online (Sandbox Code Playgroud)

我可以使用原始SQL实现这一点,但我想使用Laravel方法,如果可能的话......但是我找不到它,可能它还没有在版本5中实现它.

小智 23

将其重置为不可为空.你可以试试这个.

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

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('mytable', function(Blueprint $table) {
    /* By default it's NOT NULL */
        $table->string('mycolumn')->nullable(false)->change(); // <--- here
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为这个约束不起作用,因为您允许在列中为空。因此,当您回滚时,如果您的数据库行之一在该列中具有 null 值(正如您所允许的那样),那么当您回滚时,它将尝试使该字段不可为 null ,但由于某些值为 null ,它会失败。 (3认同)