在Laravel中获取列类型

时间:2014-09-15 20:38:18

标签: php mysql laravel

我正在创建一个Laravel项目,我需要动态检索(MySQL)数据库中某些表的列名及其类型。目前,这是我的解决方案:

$columnTypes = array();
$columns = Schema::getColumnListing($tableName);
foreach($columns as $columnName) {
    $columnTypes[$columnName] = DB::connection()->getDoctrineColumn($tableName, $columnName)->getType()->getName();
}

不幸的是,这需要大量的查询,因此需要很多时间(每张表最多约100毫秒)。

是否有更快的方法来检索列的类型?

2 个答案:

答案 0 :(得分:8)

思考,更快将使用(对于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);
  } 
}

答案 1 :(得分:1)

运行“composer require doctrine / dbal”,然后在模型中编写此函数:

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();
}