はじめに
この記事はLaravelを使ったテーブル名一覧や各カラム詳細情報の取得方法についての解説記事です。
動作確認環境
- PHP 8.0
- Laravel 8.0
※下位環境でも動作する場合がございます
全テーブル情報の取得
use DB;
// 全スキーマ情報を取得
$schema = DB::connection()->getDoctrineSchemaManager();
// テーブル名一覧を取得
$tableNames = $schema->listTableNames();
foreach ($tableNames as $tableName) {
// テーブル情報を取得
$schema = DB::connection()->getDoctrineSchemaManager();
$table = $schema->listTableDetails($tableName);
// カラム情報を取得
$columns = $table->getColumns();
$columnNames = [];
$columnComment = [];
foreach ($columns as $column) {
$columnNames[] = $column->getName();
$columnComment[] = $column->getComment();
}
}
各カラム情報
$column->get****()とメソッドを呼び出すことでカラムのそれぞれの詳細を取得することができます。
array:2 [
"id" => Doctrine\DBAL\Schema\Column^ {#858
#_type: Doctrine\DBAL\Types\IntegerType^ {#875}
#_length: null
#_precision: 10
#_scale: 0
#_unsigned: false
#_fixed: false
#_notnull: false
#_default: null
#_autoincrement: false
#_platformOptions: []
#_columnDefinition: null
#_comment: "hoge1"
#_customSchemaOptions: []
#_name: "id"
#_namespace: null
#_quoted: false
}
"name" => Doctrine\DBAL\Schema\Column^ {#886
#_type: Doctrine\DBAL\Types\IntegerType^ {#875}
#_length: null
#_precision: 10
#_scale: 0
#_unsigned: false
#_fixed: false
#_notnull: false
#_default: null
#_autoincrement: false
#_platformOptions: []
#_columnDefinition: null
#_comment: "hoge2"
#_customSchemaOptions: []
#_name: "name"
#_namespace: null
#_quoted: false
}
]