php laravel 4 -> 获取列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19951787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:16:45  来源:igfitidea点击:

laravel 4 -> get column names

phpmysqldatabaselaravellaravel-4

提问by Centurion

How to get column names of a table in an array or object in Laravel 4 , using Schema, DB, or Eloquent.

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

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

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

Thx.

谢谢。

回答by Antonio Carlos Ribeiro

New Answer

新答案

At the time I gave this answer Laravel hadn't a way to do this directly, but now you can just:

在我给出这个答案的时候,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.

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

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

然后仍然没有真正的选择,所以我不得不深入到数据库级别,这是我的 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;
    }

}

Use it doing:

使用它做:

$model = User::find(1);

dd( $model->getAllColumnsNames() );

回答by The Alpha

You may try Schema::getColumnListing('tablename'):

你可以试试Schema::getColumnListing('tablename')

$columns = Schema::getColumnListing('users'); // users table
dd($columns); // dump the result and die

Result would be something like this depending on your table:

结果将是这样的,具体取决于您的表:

array (size=12)
  0 => string 'id' (length=2)
  1 => string 'role_id' (length=7)
  2 => string 'first_name' (length=10)
  3 => string 'last_name' (length=9)
  4 => string 'email' (length=5)
  5 => string 'username' (length=8)
  6 => string 'password' (length=8)
  7 => string 'remember_token' (length=14)
  8 => string 'bio' (length=3)
  9 => string 'created_at' (length=10)
  10 => string 'updated_at' (length=10)
  11 => string 'deleted_at' (length=10)

回答by ceejayoz

You can dig down into DB's Doctrine instance.

您可以深入了解 DB 的 Doctrine 实例。

$columns = DB::connection()
  ->getDoctrineSchemaManager()
  ->listTableColumns('table');

foreach($columns as $column) {
  print $column->getName();
  print $column->getType()->getName();
  print $column->getDefault();
  print $column->getLength();
}

edit:Doctrine is no longer (as of L4.1) installed by default (it's a 'suggested' rather than 'required' package), but can be added to your composer.jsonas doctrine/dbalto retain this functionality.

编辑:默认情况下不再安装 Doctrine(从 L4.1 开始)(它是“建议的”而不是“必需的”包),但可以添加到您的composer.jsonas 中doctrine/dbal以保留此功能。

回答by windmaomao

I know it might not be the answer for everyone, but maybe you can grab one record, and get all keys of the data. Ex.

我知道这可能不是每个人的答案,但也许您可以抓取一条记录,并获取数据的所有键。前任。

array_keys(User::first()->toArray());

回答by Sajan Parikh

I think there's a couple different options, if you are using an Eloquent model, you can look at the getAccessibleAttributes()method, which in theory would give you all the columns of a model consider Eloquent seems them as properties.

我认为有几个不同的选择,如果您使用的是 Eloquent 模型,您可以查看该getAccessibleAttributes()方法,理论上该方法将为您提供模型的所有列,将 Eloquent 视为属性。

For example, you'd be able to do something like this for your users table on a User Eloquent model.

例如,您可以在 User Eloquent 模型上为您的 users 表执行类似的操作。

$user = // Retrieve your User model.
$columns = User->getAccessibleAttributes();

Another Eloquent method to look at that's similar, but doesn't have the 'accessibility' requirement is the attributesToArray()method. The returned array of which should have your columns as a key. Then you can use the PHP function array_keys()to build an array of the keys, which would be your columns.

另一个类似的 Eloquent 方法是方法,但没有“可访问性”要求attributesToArray()。返回的数组应该以您的列作为键。然后您可以使用 PHP 函数array_keys()构建一个键数组,这将是您的列。

$user = // Retrieve your User model.
$columns = array_keys(User::attributesToArray());

回答by 1210mk2

If you have a Model instance you can retrieve like following:

如果你有一个 Model 实例,你可以像下面这样检索:

    $table_name = $model->getTable();
    $connection = $model->getConnection();
    $schemaBulder = $connection->getSchemaBuilder();

    $columns_array = $schemaBulder->getColumnListing($table_name);

works for Laravel 5

适用于 Laravel 5

回答by gvsrepins

You also can try this:

你也可以试试这个:

abstract class BaseModel extends Eloquent {

public function getColumnsNames()
{
    $connection = DB::connection();
    $connection->getSchemaBuilder();

    $table   = $connection->getTablePrefix() . $this->table;
    $grammar = $connection->getSchemaGrammar();
    $results = $connection->select($grammar->compileColumnExists(), array($connection->getDatabaseName(), $table));

    return $connection->getPostProcessor()->processColumnListing($results);
}
}

回答by adam

I use SQL Server and the Schema way worked for me:

我使用 SQL Server 和 Schema 方式为我工作:

$columns = array_keys(Schema::getConnection()
->getDoctrineSchemaManager()
->listTableColumns($yourModel->getTable()) );