无法更新子行

时间:2019-11-12 07:28:46

标签: php mysql laravel

我很久以前创建了lessons表。现在,我想为表课程添加一个新的user_id列,它引用id表上的users

首先,我创建了add_profile_to_lessons迁移文件,并添加了代码以创建新列。

lessons

if ( !Schema::hasTable('lessons') ) {
    Schema::create('lessons', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('course_id')->unsigned()->nullable();
        $table->foreign('course_id', '54419_596eedbb6686e')->references('id')->on('courses')->onDelete('cascade');
        $table->string('title')->nullable();
        $table->string('slug')->nullable();
        $table->string('lesson_image')->nullable();
        $table->text('short_text')->nullable();
        $table->text('full_text')->nullable();
        $table->integer('position')->nullable()->unsigned();
        $table->tinyInteger('free_lesson')->nullable()->default(0);
        $table->tinyInteger('published')->nullable()->default(0);

        $table->timestamps();
        $table->softDeletes();

        $table->index(['deleted_at']);
    });
}

users

if ( !Schema::hasTable('users') ) {
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email');
        $table->string('password');
        $table->string('remember_token')->nullable();

        $table->timestamps();

    });
}

我创建的用于在add_profile_to_lessons迁移文件中添加新列的架构

Schema::table('lessons', function (Blueprint $table) {
    $table->unsignedInteger('user_id')->after('course_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

当我执行php artisan migration命令时,出现此错误

  

[Illuminate \ Database \ QueryException] SQLSTATE [23000]:完整性   约束违反:1452无法添加或更新子行:外部   键约束失败(quicklms#sql-d94_102,CONSTR AINT   lessons_user_id_foreign外键(user_id)参考users   (id)在DELETE CASCADE上(SQL:更改表lessons添加约束   lessons_u ser_id_foreign个外键(user_id)引用   usersid)在删除级联上)

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。当执行命令时,我看到已经创建了user_id列,并将所有值分配为零。<​​/ p>

所以首先我将user_id值零更改为users表中的一些现有值。 然后,将下面的代码放在add_profile_to_lessons迁移文件中,并执行了命令php artisan migrate,它可以正常工作^ _ ^

Schema::table('lessons', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });