diff --git a/framework/core/migrations/2019_10_12_195349_change_posts_add_discussion_foreign_key.php b/framework/core/migrations/2019_10_12_195349_change_posts_add_discussion_foreign_key.php new file mode 100644 index 000000000..0c5db4a5e --- /dev/null +++ b/framework/core/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']); + }); + } +];