laravel 将 eloquent 集合到自定义数组的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16523323/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:46:27  来源:igfitidea点击:

The best way to make eloquent collection to custom array

laravellaravel-4eloquent

提问by Benas Radzevicius

What is the best way to make Object::all()to array('object_id', 'object_name')? I need a nice code to use eloquent collection for SELECT: {{ Form:select('objects', $custom_array) }}. Is a for loop the only way to do that ?

是什么力量让最好的方式Object::all()array('object_id', 'object_name')?我需要一个很好的代码来为 SELECT: 使用 eloquent 集合{{ Form:select('objects', $custom_array) }}。for 循环是唯一的方法吗?

回答by Holger Weis

I think you are looking for toArray():

我认为您正在寻找toArray()

User::all()->toArray();

http://four.laravel.com/docs/eloquent#converting-to-arrays-or-json

http://four.laravel.com/docs/eloquent#converting-to-arrays-or-json

To get an array that can be directly used with Form::select(), you can use the following:

要获得可以直接与 一起Form::select()使用的数组,可以使用以下命令:

$contacts = Contact::orderBy('name')->lists('name', 'id');
$contacts = count($contacts) > 0 ? $contacts : array();

{{ Form::select('contact', $contacts) }}