Make another migration to establish to foreign key relationships after the two other migrations have run
How to deal with migrating tables when both must have relationship between them
Hello everyone!
I've just changed the structure of 2 tables in my database. One of them is reviews table and the other is review_reports table. Both of them doesn't exists right now in my database. Both of them have relationship to the other one.
reviews:
Schema::create('reviews', function (Blueprint $table) {
....
$table->bigInteger('removed_because_of_report_id')->unsigned()->nullable();
....
$table->foreign('removed_because_of_report_id')->references('id')->on('review_reports');
});
review_reports
Schema::create('review_reports', function (Blueprint $table) {
...
$table->unsignedBigInteger('review_id');
...
$table->foreign('review_id')->references('id')->on('reviews');
});
And obviously when I try to run php artisan migrate I get the following error when it came to reviews table:
Undefined table: 7 ERROR: relation "review_reports" does not exist (SQL: alter table "reviews" add constraint "reviews_removed_because_of_report_id_foreign" foreign key ("removed_because_of_report_id") references "review_reports" ("id"))
And when I try to manually migrate the review_reports I get:
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "reviews" does not exist (SQL: alter table "review_reports" add constraint "review_reports_review_id_foreign" foreign key ("review_id") references "reviews" ("id"))
How can I deal with that? Theoretically I can migrate no table at this point because they both need each other in order to join the database.
Try this, it will work:
reviews:
Schema::create('reviews', function (Blueprint $table) {
....
....
});
review_reports
Schema::create('review_reports', function (Blueprint $table) {
...
$table->unsignedBigInteger('review_id');
...
$table->foreign('review_id')->references('id')->on('reviews');
});
Schema::table('reviews', function (Blueprint $table) {
$table->bigInteger('removed_because_of_report_id')->unsigned()->nullable();
$table->foreign('removed_because_of_report_id')->references('id')->on('review_reports');
});
Basically, it is executing another migration to edit the reviews table, once both the initial tables are created. ( @tykus suggested the same )
Please or to participate in this conversation.