问题
I want to populate a <select>
element using the results from my categories
table. In order to do that I use the following code.
$catlist = Categories::where('type','=',$content_type)
->get(array('id','name'))->toArray();
The result structure is an array of rows.
array
0 =>
array
'id' => int 1
'name' => string 'article'
1 =>
array
'id' => int 2
'name' => string 'news'
A foreach
statement surely would solve my problem but I'm looking for a better solution.
回答1:
You could use the lists(string $column [, string $key ]) method for this, found under "Retrieving A List Of Column Values" in the documentation...
$catlist = Category::where('type', $content_type)->lists('name');
回答2:
try to add static function on you category model
public static function genlist()
{
$catlist = [];
foreach (self::all() as $cat)
{
$catlist[$cat->id] = $cat->name;
}
return $catlist;
}
view
{{ Form::select('cat_id', Category::genlist()) }}
this works to me, and hope will work to you also
来源:https://stackoverflow.com/questions/16669943/populate-select-element