Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching column types in Laravel

Tags:

php

mysql

laravel

I'm creating a Laravel project for which I need to dynamically retrieve column names and their types for some tables in the (MySQL) database. 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, this requires a lot of queries, and thus a lot of time (up to ~100ms per table).

Is there a faster way to retrieve the types of the columns?

like image 585
nhaarman Avatar asked Jan 09 '23 19:01

nhaarman


1 Answers

Think, more fast will be using (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);
  } 
}
like image 198
voodoo417 Avatar answered Jan 18 '23 08:01

voodoo417