N
N
nicklayk2018-03-30 14:13:17
MySQL
nicklayk, 2018-03-30 14:13:17

How to link two tables one to one?

There are two tables: 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();
        });

That is, I want my tables to have indexes and fields to point to each other.
After: 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")
How to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nicklayk, 2018-03-30
@nicklayk

The problem is that I'm trying to create a table with a foreign key that points to a table that hasn't been created yet.

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');
        });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question