在我给出这个答案的时候, Laravel还没有直接做到这一点的方法 ,但是现在您可以:
旧答案$columns = Schema::getColumnListing('users');
使用属性将不起作用,因为如果您这样做
$model = new ModelName;
您没有为该模型设置任何属性,您将一无所获。
然后仍然没有真正的选择,因此我不得不深入到数据库级别,这是我的baseModel:
<?phpclass 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() );
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)