Laravel:如何遍历 ORM 的字段和关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13344030/
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 can I loop through the fields and relations of an ORM
提问by jaget
In Laravel if I create an ORM for a table, lets say pages
在 Laravel 中,如果我为表创建 ORM,可以说页面
Is there a way to list/loop through all the tables fields and their values (from the database), and on top of that is there a way to list/loop through all the relationships.
有没有办法列出/循环遍历所有表字段及其值(来自数据库),最重要的是有一种方法列出/循环遍历所有关系。
Is there a way to access the attributes/fields of an orm object such as:
有没有办法访问 orm 对象的属性/字段,例如:
foreach($pages->fields_array as $f){
//do something with field
}
What I'm trying to do is get a dynamic list of fields and their values so I can auto build a form.
我想要做的是获取字段及其值的动态列表,以便我可以自动构建表单。
As for the relations I am trying to loop through all related tables to create a dropdown list of linked tables.
至于关系,我试图遍历所有相关表以创建链接表的下拉列表。
回答by keithics
in Laravel 3 you can loop with $page->attributes
在 Laravel 3 中,您可以使用 $page->attributes 循环
But not in Laravel 4.
但不是在 Laravel 4 中。
Just do this instead and do for each after.
只需执行此操作,然后为每个执行此操作。
$page->toArray(); // it will convert the model object into an array :)
http://laravel.com/docs/eloquent#converting-to-arrays-or-json
http://laravel.com/docs/eloquent#converting-to-arrays-or-json
回答by afarazit
Here's how i loop through an object and it's relations (images is the relation for this example)
这是我如何遍历对象及其关系(图像是此示例的关系)
$page = Page::with('images')->first();
// Laravel 4
foreach($page->attributes as $attr)
{
dd($attr);
}
// Laravel 5
foreach($page->getAttributes() as $attr)
{
dd($attr);
}