2
4

More than 3 years have passed since last update.

Laravelでデータベースのテーブル名やカラム詳細情報を取得する方法

Last updated at Posted at 2021-05-28

はじめに

この記事は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
  }
]
2
4
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
2
4