如果您的模型填充了数据,您可以:
$announcement = Announcement::find(1);
$attributes = $announcement->getAttributes();
isset($attributes['created_by']);
对于空模型(新模型),不幸的是,您将不得不使用一个小的黑客来获取列。将此方法添加到基本模型:
<?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->getTable()."'";
$column_name = 'column_name';
$reverse = true;
break;
case 'mysql':
$query = 'SHOW COLUMNS FROM '.$this->getTable();
$column_name = 'Field';
$reverse = false;
break;
case 'sqlsrv':
$parts = explode('.', $this->getTable());
$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] = $column->$column_name; // setting the column name as key too
}
if($reverse)
{
$columns = array_reverse($columns);
}
return $columns;
}
}
从中扩展模型:
class Announcement extends BaseModel {
}
然后,您将能够:
$columns = $announcement->getAllColumnsNames();
isset($columns['created_by']);