【问题标题】:Make column not nullable in a Laravel 5 migration在 Laravel 5 迁移中使列不可为空
【发布时间】:2016-01-07 05:36:18
【问题描述】:

我发现这个问题与我的 Make column not nullable in a Laravel migration 非常相似,尽管它已经快 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(); 
    });
}

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

【问题讨论】:

  • 从我在源代码中可以看到,nullable() 没有对立面,因此您可能需要使用 Db 门面进行原始查询。
  • 谢谢@Amo,恐怕你是对的。

标签: php sql laravel-5


【解决方案1】:

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

/**
 * 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
    });
}

【讨论】:

  • 我认为这个约束不起作用,因为你允许在你的列中为空。因此,当您回滚时,如果您的 db 行在该列中有一个 null 值(如您允许的那样),那么当您回滚时,它将尝试使该字段不可为空,但由于某些值为 null ,它将失败。
【解决方案2】:

默认情况下它的NOT NULL,所以你应该试试这个。

/**
 * 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')->change(); 
    });
}

【讨论】:

  • 我也认为这可能有效,但不幸的是它不会恢复到默认值
  • 好主意,但在 Laravel 5.7 中也不起作用 - 只是为了节省其他时间,$table->unsignedInteger('foreign_id')->change();不会将该列恢复为必需的(不可为空)。
猜你喜欢
  • 2012-12-10
  • 2014-08-16
  • 2016-03-14
  • 2017-10-03
  • 2021-03-20
  • 2019-05-29
  • 2020-11-11
  • 2023-03-19
  • 2011-08-23
相关资源
最近更新 更多