From f7feea496d319eb8181d1f2f2e9dee6170319e95 Mon Sep 17 00:00:00 2001 From: David Sevilla Martin Date: Sat, 12 Oct 2019 15:57:35 -0400 Subject: [PATCH] Add discussion_id foreign key to posts table --- ...hange_posts_add_discussion_foreign_key.php | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 migrations/2019_10_12_195349_change_posts_add_discussion_foreign_key.php diff --git a/migrations/2019_10_12_195349_change_posts_add_discussion_foreign_key.php b/migrations/2019_10_12_195349_change_posts_add_discussion_foreign_key.php new file mode 100644 index 000000000..0c5db4a5e --- /dev/null +++ b/migrations/2019_10_12_195349_change_posts_add_discussion_foreign_key.php @@ -0,0 +1,28 @@ + function (Builder $schema) { + // Delete rows with non-existent entities so that we will be able to create + // foreign keys without any issues. + $connection = $schema->getConnection(); + $connection->table('posts') + ->orWhereNotExists(function ($query) { + $query->selectRaw(1)->from('discussions')->whereColumn('id', 'discussion_id'); + }) + ->delete(); + + + $schema->table('posts', function (Blueprint $table) { + $table->foreign('discussion_id')->references('id')->on('discussions')->onDelete('cascade'); + }); + }, + + 'down' => function (Builder $schema) { + $schema->table('posts', function (Blueprint $table) { + $table->dropForeign(['discussion_id']); + }); + } +];