Laravel数据库迁移在很多列中为空

时间:2019-01-03 04:30:36

标签: laravel

我正在为具有很多列的表编写Laravel迁移文件,而其中大多数应为nullable(不幸的是有些)。这导致我编写重复的代码,例如:

Schema::create('my_table', function (Blueprint $table) {
    $table->increments('id');
    $table->string('col_1')->nullable();
    $table->string('col_2')->nullable();
    $table->string('col_3')->nullable();
    // ...
    // (Note that col_1 etc can be different names instead of incrementing by no.)
});

是否有一种方法可以默认设置表蓝图nullable(而无需显式调用nullable())或一次将nullable分配给所有需要的列?还是有其他方法(最好是在迁移文件中)来做到这一点?

1 个答案:

答案 0 :(得分:1)

实际上Illuminate\Database\Schema\Blueprint类使用的是macroable特性

  

一种特性,可以向类中动态添加方法。

这是我们可以利用此功能的方法。

  1. 宏方法添加到service provider's boot() method(例如:AppServiceProvider

    use Illuminate\Database\Schema\Blueprint;
    Blueprint::macro('defaultNull', function(...$columns){
       foreach($columns as $column) {
           $column->nullable();
       }
    });
    
  2. 在迁移类中使用我们的宏方法:现在,您可以将所有“ nullable”列添加到defaultNull宏方法中,如下所示:< / p>

    Schema::create('my_table', function (Blueprint $table) {
        $table->increments('id');
        $table->defaultNull(
            $table->string('col_1'), 
            $table->string('col_2'), 
            $table->string('col_3')
        );
    });