SQLSTATE [HY000]: общая ошибка: 1005 Не удается создать таблицу `laravel_work_faranesh`.`learnings`

привет, я использую эту миграцию и вижу эту ошибку

Schema::create('learnings', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('course_id')->unsigned();
            $table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });

ошибка:

 SQLSTATE[HY000]: General error: 1005 Can't create table `laravel_work_faranesh`.`learnings` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tab
le `learnings` add constraint `learnings_course_id_foreign` foreign key (`course_id`) references `courses` (`id`) on delete cascade)

и, конечно, мигрировать

Schema::create('courses', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade');   
    });

person tohid    schedule 18.05.2020    source источник
comment
Убедитесь, что идентификатор в таблице курсов имеет тот же тип, что и курс_ид в обучении (без знака bigInt).   -  person kopz    schedule 18.05.2020
comment
Какова ваша courses миграция?   -  person sta    schedule 18.05.2020
comment
@kopz я добавляю миграцию курса... наверх   -  person tohid    schedule 18.05.2020
comment
@TalhaF. я добавляю перенос курса... наверх   -  person tohid    schedule 18.05.2020
comment
Проверьте тип идентификатора в курсах в вашей базе данных. Вы также не указали свою версию Laravel. course_id и user_id в $table-›integer('')-›unsigned();   -  person kopz    schedule 18.05.2020
comment
не работает SQLSTATE [HY000]: общая ошибка: 1005 не удается создать таблицу laravel_work_faranesh.learnings (ошибка: 150 ограничение внешнего ключа неправильно сформировано) (SQL: изменить таблицу learnings добавить ограничение learnings_course_id_foreign внешний ключ (course_id) ссылки courses (id) при удалении каскада)   -  person tohid    schedule 18.05.2020


Ответы (2)


Попробуйте создать миграцию следующим образом:

Сначала создайте Курсы, а затем Обучение.

Schema::create('courses', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned();
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade');   
        });


Schema::create('learnings', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('course_id')->unsigned();
            $table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });

Потому что вы используете unsigned дважды для одного столбца.

person bjeftic    schedule 18.05.2020
comment
не работает ... ошибка SQLSTATE [HY000]: Общая ошибка: 1005 Невозможно создать таблицу laravel_work_faranesh.learnings (ошибка: 150 Ограничение внешнего ключа сформировано неправильно) (SQL: изменить таблицу learnings добавить ограничение learnings_course_id_foreign ссылки на внешний ключ (course_id) courses (id) при удалении каскада) - person tohid; 18.05.2020
comment
Я обновил код, и, пожалуйста, сначала создайте курсы, а затем таблицу обучения. - person bjeftic; 18.05.2020

Вы можете устанавливать внешние ключи только в уже существующих таблицах. Попробуй это:

    Schema::create('courses', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id')->unsigned();
    });
    Schema::table('courses', function (Blueprint $table) {
        $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade');
    });

А также:

        Schema::create('learnings', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('course_id')->unsigned();
            $table->bigInteger('user_id')->unsigned();
            $table->timestamps();
        });
        Schema::table('learnings', function (Blueprint $table) {
            $table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
person AndreyBlog    schedule 18.05.2020