I created the lessons
table long time before. now i would like to add a new user_id
column for table lessons,which refer the id
on users
table.
first i created the add_profile_to_lessons
migration file and added the code to create a new column.
The lessons
table
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']);
});
}
The users
table
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();
});
}
The schema i created to add a new column in add_profile_to_lessons
migration file
Schema::table('lessons', function (Blueprint $table) {
$table->unsignedInteger('user_id')->after('course_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
When i executed php artisan migrate command, i get this error
[Illuminate\Database\QueryException] SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
quicklms
.#sql-d94_102
, CONSTR AINTlessons_user_id_foreign
FOREIGN KEY (user_id
) REFERENCESusers
(id
) ON DELETE CASCADE) (SQL: alter tablelessons
add constraintlessons_u ser_id_foreign
foreign key (user_id
) referencesusers
(id
) on delete cascade)