Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
class GenerateDropForeignKeyMigration extends Command
{
protected $signature = 'migration';
protected $description = 'Command description';
public function handle()
{
$data = DB::select(
"
SELECT
TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_SCHEMA = ?",
[config('database.connections.mysql.database')]
);
$results = collect($data)->groupBy('TABLE_NAME');
$text = '';
foreach ($results as $table => $data) {
$text .= sprintf(
"Schema::table('%s', function (Blueprint \$table) {
",
$table
);
foreach ($data as $item) {
$text .= sprintf(" \$table->dropForeign('%s');\n", $item->CONSTRAINT_NAME);
}
$text .= "});\n";
}
Storage::put('migration_stuff.txt', $text);
}
}
@jamesmills
Copy link
Author

jamesmills commented Sep 12, 2022

This dumps something like the below in storage/app/migration_stuff.txt

Schema::table('team_invitations', function (Blueprint $table) {
    $table->dropForeign('team_invitations_team_id_foreign');
});
Schema::table('placement_webhook', function (Blueprint $table) {
    $table->dropForeign('placement_webhook_placement_id_foreign');
    $table->dropForeign('placement_webhook_webhook_id_foreign');
});
Schema::table('site_partner_buckets', function (Blueprint $table) {
    $table->dropForeign('site_partner_buckets_bucket_id_foreign');
    $table->dropForeign('site_partner_buckets_partner_id_foreign');
    $table->dropForeign('site_partner_buckets_site_id_foreign');
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment