Laravel使用SQLite迁移'无法添加默认值NULL的NOT NULL列' [英] Laravel migration with SQLite 'Cannot add a NOT NULL column with default value NULL'

查看:139
本文介绍了Laravel使用SQLite迁移'无法添加默认值NULL的NOT NULL列'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 since I understood the seeding happens after all the migrations are completed so why is it complaining about this issue which would only arise if data was already present in the database.

我的两次迁移是

首次迁移

  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怪癖.根据

It looks like this is a SQLite oddity. According to a Laracast forum thread about the same issue:

从头开始添加表时,可以指定NOT NULL.但是,添加列时无法执行此操作. SQLite的规范说必须为此设置默认值,这是一个糟糕的选择.

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文档,我发现:

Looking further to the SQLite ALTER TABLE docs, I found:

如果指定了NOT NULL约束,则该列必须具有非NULL的默认值.

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

我想在SQLite的世界中,不提供默认值与说默认值应为NULL是相同的(相反,这意味着此不可为空的列没有默认值,因此值必须在每次插入时为其提供.

I suppose in the world of SQLite, not providing a default value is the same thing as saying the default value should be NULL (as opposed to meaning there is no default value for this non-nullable column, so a value must be provided for it on each insert).

如果您需要在现有表中添加不可为空的列,则SQLite似乎只会使您处于错误状态,该列也不应具有默认值.

It seems SQLite simply leaves you in a bad state if you need to add a non-nullable column to an existing table, which column should also not have a default value.

这篇关于Laravel使用SQLite迁移'无法添加默认值NULL的NOT NULL列'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆