1
3

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 3 years have passed since last update.

【laravel】 DBの存在するテーブルとカラムとカラムの型を取得するあとdoctrine/dbalでjson型が扱えない件

Last updated at Posted at 2019-11-26

環境

MySQL 5.7
Laravel 5.8

存在するテーブル

tableNames = [];
foreach (DB::select('SHOW TABLES') as $table) {
	$dbName = config('database.connections.mysql.database');
	$tableNames[] = $table->{'Tables_in_' . $dbName};
}

存在するカラムとその型

型を取得


// 存在するカラムを取得
$columns = Schema::connection('mysql')->getColumnListing($tableName);

$columnTypes = [];
foreach ($columns as $column) {
	// カラムタイプを取得
	$columnTypes[$column] = Schema::connection('mysql')->getConnection()->getDoctrineColumn($tableName, $column)->toArray()['type'];
}

int の場合 Doctrine\DBAL\Types\IntegerType のようにとれる。
これはSQLの型とPHPの型をマッピングするクラス。

型判定

if ($type instanceof Doctrine\DBAL\Types\StringType) {
	// ごにょごにょ
}

json型でエラー

Doctrine DBALが2.4以下だとjson型がサポート外とのこと。
エラーが出るので以下のようにjson_arrayにマッピングさせると扱えるようになる。


DB::getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('json', 'json_array');
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?