@nicklayk

Как связать две таблицы один к одному?

Есть две таблицы: projects
Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('tender_id')->unsigned();
            $table->string('fullname')->nullable(true);

            $table->foreign('tender_id')->references('id')->on('tenders');
            
            $table->timestamps();
        });

tenders:
Schema::create('tenders', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('project_id')->unsigned();
            $table->string('fullname')->nullable(true);
            
            $table->foreign('project_id')->references('id')->on('projects');

            $table->timestamps();
        });


То есть я хочу, чтобы у меня в таблицах были индексы и поля указывали на друга на друга.

После: php artisan migrate:fresh

Dropped all tables successfully.
Migration table created successfully.

In Connection.php line 664:

SQLSTATE[HY000]: General error: 1005 Can't create table `crm_magio`.`#sql-2e48_1e8` (errno: 150 "Foreign key constr
aint is incorrectly formed") (SQL: alter table `tenders` add constraint `tenders_project_id_foreign` foreign key (`
project_id`) references `projects` (`id`))

In Connection.php line 458:

SQLSTATE[HY000]: General error: 1005 Can't create table `crm_magio`.`#sql-2e48_1e8` (errno: 150 "Foreign key constr
aint is incorrectly formed")

Как исправить?
  • Вопрос задан
  • 226 просмотров
Решения вопроса 1
@nicklayk Автор вопроса
Проблема в том, что я пытаюсь создать таблицу с внешним ключом, который ведет на ещё не созданную таблицу.

Schema::create('tenders', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('project_id')->unsigned();
            $table->string('fullname')->nullable(true);
         
            $table->timestamps();
        });

Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('tender_id')->unsigned();
            $table->string('fullname')->nullable(true);

            $table->foreign('tender_id')->references('id')->on('tenders');
            
            $table->timestamps();
        });

        Schema::table('tenders', function (Blueprint $table) {
            $table->foreign('project_id')->references('id')->on('projects');
        });
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы