First Commit
This commit is contained in:
+71
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Symfony\Component\Console\Helper\Table;
|
||||
|
||||
class DbRelationshipsCommand extends Command
|
||||
{
|
||||
protected static $defaultName = 'db:relationships';
|
||||
protected static $defaultDescription = 'Exibe as chaves estrangeiras de uma tabela';
|
||||
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->addArgument('table', InputArgument::REQUIRED, 'O nome da tabela');
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$tableName = $input->getArgument('table');
|
||||
$connection = Capsule::connection();
|
||||
$dbName = $connection->getDatabaseName();
|
||||
|
||||
$output->writeln("<info>Chaves Estrangeiras da Tabela: {$tableName}</info>");
|
||||
|
||||
try {
|
||||
$query = "
|
||||
SELECT
|
||||
COLUMN_NAME,
|
||||
CONSTRAINT_NAME,
|
||||
REFERENCED_TABLE_NAME,
|
||||
REFERENCED_COLUMN_NAME
|
||||
FROM
|
||||
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
|
||||
WHERE
|
||||
TABLE_SCHEMA = ? AND
|
||||
TABLE_NAME = ? AND
|
||||
REFERENCED_TABLE_NAME IS NOT NULL";
|
||||
|
||||
$relationships = $connection->select($query, [$dbName, $tableName]);
|
||||
|
||||
if (empty($relationships)) {
|
||||
$output->writeln('<comment>Nenhuma chave estrangeira encontrada para esta tabela.</comment>');
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$table = new Table($output);
|
||||
$table->setHeaders(['Coluna', 'Constraint', 'Tabela Referenciada', 'Coluna Referenciada']);
|
||||
|
||||
foreach ($relationships as $rel) {
|
||||
$table->addRow([
|
||||
$rel->COLUMN_NAME,
|
||||
$rel->CONSTRAINT_NAME,
|
||||
$rel->REFERENCED_TABLE_NAME,
|
||||
$rel->REFERENCED_COLUMN_NAME
|
||||
]);
|
||||
}
|
||||
|
||||
$table->render();
|
||||
return Command::SUCCESS;
|
||||
} catch (\Exception $e) {
|
||||
$output->writeln("<error>Erro ao buscar relacionamentos: " . $e->getMessage() . "</error>");
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user