laravel 4 - >获取列名称 [英] laravel 4 -> get column names
本文介绍了laravel 4 - >获取列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Schema,DB或Eloquent在Laravel 4中的数组或对象中获取表的列名。
How to 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.
Thx。
推荐答案
新答案
当时我给了这个答案 Laravel没有办法直接这样做您可以:
$columns = Schema::getColumnListing('users');
旧回答
t工作,因为如果你做
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() );
这篇关于laravel 4 - >获取列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文