6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Zend\Db でデータベースのリバースエンジニアリング

6
Posted at
<?php
use Zend\Db\Adapter\Adapter;
use Zend\Db\Metadata\Metadata;

$adapter = new Adapter([
    'driver' => 'Mysqli',
    'database' => 'sore',
    'username' => 'ore',
    'password' => 'are',
]);

$metadata = new Metadata($adapter);

foreach ($metadata->getTables() as $table) {
    echo $table->getName(), PHP_EOL;
    show_column_infos($table);
}

function get_key_infos($table) {

    $keyInfos = ['primary' => [], 'foreign' => []];
    foreach ($table->getConstraints() as $constraint) {
        if ($constraint->isPrimaryKey()) {
            $keyInfos['primary'] = array_flip($constraint->getColumns());
        }
        if ($constraint->isForeignKey()) {
            $keyInfos['foreign']['cols'] = implode(', ', $constraint->getColumns());
            $keyInfos['foreign']['name'] = $constraint->getReferencedTableName();
            $keyInfos['foreign']['refs'] = implode(', ', $constraint->getReferencedColumns());
        }
    }
    return $keyInfos;
};

function show_column_infos($table) {
    $keyInfos = get_key_infos($table);
    foreach ($table->getColumns() as $column) {
        $name = $column->getName();
        if (isset($keyInfos['primary'][$name])) {
            echo " * ", $name, PHP_EOL;
        } else {
            echo "   ", $name, PHP_EOL; 
        }
    }

    if ($foregin = $keyInfos['foreign']) {
        echo "     ... fkey ( {$foregin['cols']} ) ref {$foregin['name']} ( {$foregin['refs']} )" . PHP_EOL;
    }
}

Doctrine でデータベースのリバースエンジニアリング - http://qiita.com/ngyuki/items/4fd29d58dc90100c55b8

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?