php laravel:如何获取 eloquent 模型的列名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45818177/
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
laravel:how to get columns name of eloquent model?
提问by Jatin Parmar
I am using laravel 5.2 ,i want to get all the column (attribute) name of selected eloquent model,is there way to do this?
我正在使用 Laravel 5.2,我想获取所选 eloquent 模型的所有列(属性)名称,有没有办法做到这一点?
following is my code in controller method
以下是我在控制器方法中的代码
if($request->method=="edit")
{
/*we are in edit mode details of given news ID should be attached*/
$curNews=News::find($request->newsID);
if($curNews==null)return back()->withErrors(["Unable to Edit News:No Data Found For Given News ID"]);
foreach((array)$curNews->attributes as $key=>$val)
{
$data[$key]=$val;
}
}
return view('adminarea.news.news-addedit',$data);
回答by Kuldeep Mishra
$columns = Schema::getColumnListing('users'); // users table
dd($columns); // dump the result and die
回答by Pavel
If you want get the names of your attributes, you can try this
如果你想得到你的属性的名字,你可以试试这个
$item = News::find($request->newsID);
$attributes = array_keys($item->getOriginal());
// or
$attributes = array_keys($item->getAttributes());
回答by Jatin Parmar
don't know i am right or not, but i have overcome with following code,and its working for me.
不知道我是否正确,但我已经克服了以下代码,并且它对我有用。
if($request->method=="edit")
{
/*we are in edit mode details of given news ID should be attached*/
$curNews=News::find($request->newsID);
if($curNews==null)return back()->withErrors(["Unable to Edit News:No Data Found For Given News ID"]);
foreach($curNews->toArray() as $key=>$val)
{
$data[$key]=$val;
}
}
return view('adminarea.news.news-addedit',$data);