使用数据库表中的值生成下拉列表输入 [英] Generate drop-down list input with values from DB table
问题描述
我正在尝试使用Laravel使用MySQL表中的值生成一个下拉列表.该表很简单,有两列- id
和 category
.
I am trying to generate a drop-down list with values from a MySQL table using Laravel. The table is simple, two columns - id
and category
.
以下将检索所有记录(类别),但返回一个对象而不是数组,这是我需要的下拉代码-
The following will retrieve all of the records (categories) but returns an object rather than an array, which is what I need for the drop-down code -
$categories = Category::all();
下拉菜单的代码为:
{{ Form::select('category', $categories, $post->category_id) }}
想法?
更新
bgallagh3r建议使用foreach循环将每个类别转换为数组.他们的代码使我接近,但生成了一堆时髦的嵌套 optgroup
标记.我只能将它简化为一个 optgroup
,但这太多了.
bgallagh3r suggested using a foreach loop to convert each category to an array. Their code got me close but generated a bunch of funky nested optgroup
tags. I was able to get it down to just one optgroup
but that is one too many..
$categories = Category::all();
foreach ($categories as $cat)
{
$category = $cat->to_array();
$id = $category['id'];
$value = $category['category'];
$cats[] = array($id => $value);
}
然后,采用以下格式:
{{ Form::select('categories', $categories)}}
我最终得到了这个HTML:
I end up with this HTML:
<select name="categories">
<optgroup label="0">
<option value="1">Department News</option>
</optgroup>
<optgroup label="1">
<option value="2">General</option>
</optgroup>
...
</select>
推荐答案
您可以尝试使用列表"功能:
You can try the 'lists' function:
$ categories = Category :: lists('category','id');
(仅适用于Laravel 3)甚至省去了'id'参数,因为它将默认为Model键,请参见http://laravel.com/api/source-class-Laravel.Database.Query.html#596
(Only for Laravel 3) Or even leave out the 'id' parameter, as it will default to the Model key, see http://laravel.com/api/source-class-Laravel.Database.Query.html#596
$ categories = Category :: lists('category');
(对于Laravel 4,您确实需要第二个参数,请参见http://laravel.com/api/source-class-Illuminate.Database.Query.Builder.html#1034-1063 )
(For Laravel 4, you do need the second param, see http://laravel.com/api/source-class-Illuminate.Database.Query.Builder.html#1034-1063)
这篇关于使用数据库表中的值生成下拉列表输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!