Laravel migration with SQLite 'Cannot add a NOT NULL column with default value NULL'

前端 未结 8 697
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 23:50

Why am I getting this warning when using the SQLite driver? I have no problems with the MySQL driver but SQLite is throwing this error.

It does not make sense to me

相关标签:
8条回答
  • 2020-12-06 00:17

    All the folks solutions are good, but I wanted to find a reusable and readable way to do this, so I made a trait and hope it can help you remove some boilerplate codes out of your migrations.

    The method is $this->databaseDriverIs("driver_name_here");.

    Here is how I use it in a typical table creation migration:

    <?php
    
    use App\Traits\WithDatabaseDriver;
    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateCountryTable extends Migration
    {
      use WithDatabaseDriver;
    
      public function up()
      {
        Schema::create("country", function (Blueprint $table) {
          $table->increments("id");
          $table->string("name");
    
          $table->unique("name", "unique_country_name");
        });
    
        Schema::table("continent", function (Blueprint $table) {
          $column = $table->unsignedInteger("countryId");
    
          // This is where we apply the "fix" if 
          // the driver is SQLite
          if ($this->databaseDriverIs("sqlite")) {
            $column->nullable();
          }
    
          $table->foreign("countryId")->references("id")->on("country");
        });
      }
    
      public function down()
      {
        Schema::dropIfExists("country");
      }
    }
    

    And this is the trait that does all the job:

    <?php
    
    namespace App\Traits;
    
    trait WithDatabaseDriver
    {
      /**
       * @var string
       */
      private $driver;
    
      public function __construct()
      {
        $this->driver = config("database.default");
      }
    
      public function databaseDriverIs(string $driver): bool
      {
        return $this->driver === $driver;
      }
    }
    
    0 讨论(0)
  • 2020-12-06 00:20

    I'm not familiar with Laravel, but apparently the use of the after method to specify the order of columns appears to specifically mention ONLY MySQL (Laravel) and a discussion (GitHub) seems to point to difficulties in it's use with SQLite. It may likely be incompatible because its function: "...use the after method to specify the order of columns" design runs up against the limitation in SQLite's documentation (SQLite) for adding columns... which reads: "The new column is always appended to the end of the list of existing columns." I can't say whether assigning default values with ->default($value) can get you by or not.

    0 讨论(0)
提交回复
热议问题