Getting column types in Laravel
I am creating a Laravel project for which I need to dynamically retrieve column names and their types for some tables in a database (MySQL). Currently this is my solution:
$columnTypes = array();
$columns = Schema::getColumnListing($tableName);
foreach($columns as $columnName) {
$columnTypes[$columnName] = DB::connection()->getDoctrineColumn($tableName, $columnName)->getType()->getName();
}
Unfortunately it takes a lot of queries and therefore a lot of time (up to ~ 100ms per table).
Is there a faster way to get the column types?
+3
source to share
2 answers
Thought, it would be faster to use (for MySQL):
$tables = array[/* table list */];
foreach($tables as $table){
$table_info_columns = DB::select( DB::raw('SHOW COLUMNS FROM "'.$table.'"'));
foreach($table_info_columns as $column){
$col_name = $column['Field'];
$col_type = $column['Type'];
var_dump($col_name,$col_type);
}
}
+7
source to share
Run "composer" requires doctrine / dbal ", then write this function into the model:
public function getTableColumns() {
$builder = $this->getConnection()->getSchemaBuilder();
$columns = $builder->getColumnListing($this->getTable());
$columnsWithType = collect($columns)->mapWithKeys(function ($item, $key) use ($builder) {
$key = $builder->getColumnType($this->getTable(), $item);
return [$item => $key];
});
return $columnsWithType->toArray();
}
0
source to share