sqlite - 使用 SQLite 'Cannot add a NOT NULL column with default value NULL' 进行 Laravel 迁移

标签 sqlite laravel eloquent

为什么我在使用 SQLite 驱动程序时收到此警告?我对 MySQL 驱动程序没有任何问题,但 SQLite 会抛出此错误。

这对我来说没有意义,因为我知道播种发生在所有迁移完成之后,所以为什么它会提示这个问题,这个问题只有在数据已经存在于数据库中时才会出现。

我的两次迁移是

第一次迁移

  public function up() {
    Schema::create('users', function($table) {
      $table->increments('id');
      $table->string('username');
      $table->string('email');
      $table->string('password');
    });
  } 

第二次迁移

public function up() {
    Schema::table('users', function(Blueprint $table) {
        $table->date('birthday')->after('id');
        $table->string('last_name')->after('id');
        $table->string('first_name')->after('id');
    });
}

错误

Exception: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL (SQL: alter table "users" add column "birthday" date not null)

最佳答案

这看起来像是 SQLite 的怪事。根据Laracast forum thread about the same issue :

When adding a table from scratch, you can specify NOT NULL. However, you can't do this when adding a column. SQLite's specification says you have to have a default for this, which is a poor choice.

进一步观察 SQLite ALTER TABLE docs ,我发现:

If a NOT NULL constraint is specified, then the column must have a default value other than NULL.

我想在 SQLite 的世界里,不提供默认值和说默认值应该是 NULL 是一样的(而不是说这个不可空的列没有默认值,所以一个值 必须在每个插页上为其提供)。

如果您需要向现有表中添加不可为空的列,SQLite 似乎只会让您处于糟糕的状态,该列也不应具有默认值。

关于sqlite - 使用 SQLite 'Cannot add a NOT NULL column with default value NULL' 进行 Laravel 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20822159/

相关文章:

java - 在没有上下文的情况下在运行时创建 SQLite DB

python - 当其中一行匹配条件时如何返回数据库实体的总计数

php - 来自外部 url 源的 Laravel 4 Response::download()

mysql - 在 Laravel 的 Eloquent 或普通 SQL 中计数点

php - 如何使用 Laravel 8 查询构建器(如 eloquent)进行搜索

android - 用于多部分 SMS 的 BroadcastReceiver

python - 扁平化和解包列表

php - 导出 Excel 文件时调整列宽

laravel - 有没有办法在没有数据的月份返回 0?

php - Laravel 属于外键不起作用