laravel 你能遍历一个 eloquent 对象的属性吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26143416/
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
Can you iterate over the properties of an eloquent object?
提问by Jimmyt1988
If I have for example:
如果我有例如:
$project = new Project(); // Project is a class that extends Eloquent
$project->title;
$project->something;
Is it possible to iterate over those properties... something like this:
是否可以迭代这些属性......像这样:
foreach( $project as $key => $value )
{
echo $key;
}
I am trying to do this to achieve a unit of work for editing Eloquent models
我正在尝试这样做以实现编辑 Eloquent 模型的工作单元
回答by Steve
You can use the toArray()
method:
您可以使用以下toArray()
方法:
foreach( $project->toArray() as $key => $value )
{
echo $key;
}
http://laravel.com/docs/4.2/eloquent#converting-to-arrays-or-json
http://laravel.com/docs/4.2/eloquent#converting-to-arrays-or-json
回答by Marcin Nabia?ek
You can also use getAttributes()
method:
您还可以使用getAttributes()
方法:
foreach ($project->getAttributes() as $k => $v) {
echo $k.' '.$v."<br />";
}