如何在 Laravel 4 中获取列名?

2022-01-08 00:00:00 database php mysql laravel laravel-4

如何在 Laravel 4 中使用 Schema、DB 或 Eloquent 获取数组或对象中表的列名?

How can I get column names of a table in an array or object in Laravel 4, using Schema, DB, or Eloquent?

我好像找不到一个现成的函数,也许你有一些自定义的实现.

It seems that I can't find a ready to use function, maybe you have some custom implementations.

推荐答案

新答案

当时我给出了这个答案Laravel 没有办法直接做到这一点,但现在你可以:

$columns = Schema::getColumnListing('users');

旧答案

使用属性是行不通的,因为如果你这样做了

Old Answer

Using attributes won't work because if you do

$model = new ModelName;

您没有为该模型设置任何属性,您将一无所获.

You have no attributes set to that model and you'll get nothing.

那么仍然没有真正的选择,所以我不得不进入数据库级别,这是我的 BaseModel:

Then there is still no real option for that, so I had to go down to the database level and this is my BaseModel:

<?php

class BaseModel extends Eloquent {

    public function getAllColumnsNames()
    {
        switch (DB::connection()->getConfig('driver')) {
            case 'pgsql':
                $query = "SELECT column_name FROM information_schema.columns WHERE table_name = '".$this->table."'";
                $column_name = 'column_name';
                $reverse = true;
                break;

            case 'mysql':
                $query = 'SHOW COLUMNS FROM '.$this->table;
                $column_name = 'Field';
                $reverse = false;
                break;

            case 'sqlsrv':
                $parts = explode('.', $this->table);
                $num = (count($parts) - 1);
                $table = $parts[$num];
                $query = "SELECT column_name FROM ".DB::connection()->getConfig('database').".INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'".$table."'";
                $column_name = 'column_name';
                $reverse = false;
                break;

            default: 
                $error = 'Database driver not supported: '.DB::connection()->getConfig('driver');
                throw new Exception($error);
                break;
        }

        $columns = array();

        foreach(DB::select($query) as $column)
        {
            $columns[] = $column->$column_name;
        }

        if($reverse)
        {
            $columns = array_reverse($columns);
        }

        return $columns;
    }

}

用它来做:

$model = User::find(1);

dd( $model->getAllColumnsNames() );

相关文章