首页 > 解决方案 > 无法使用外键添加新列

问题描述

我是 laravel 的新手,向现有表添加新列时出现上述错误:

SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(schoolmanagement. #sql-314_2c,CONSTRAINT students_parentsid_foreignFOREIGN KEY ( parentsid) REFERENCES parent_names( id) ON DELETE CASCADE)(SQL:alter table students add constraint students_parentsid_foreignforeign key ( parentsid) 引用parent_names( id) 删除级联)

    public function up(){
        Schema::table('students', function (Blueprint $table)
        {
            $table->unsignedBigInteger('parentsid')->after('id');
            $table->foreign('parentsid')->references('id')->on('parent_names')->onDelete('cascade');
        });
    }


    public function down()
    {
        Schema::table('students', function (Blueprint $table) {
            //
        });
    }

只需使用外键为现有表插入一列

标签: laravel

解决方案


那是因为您试图创建一个具有外键约束但没有设置默认值的新列。因此,您可以将其设置为nullable或设置默认值(必须是parent_names表中存在的 ID)

$table->unsignedBigInteger('parentsid')->default(1);

推荐阅读