我正在尝试填充 select
Laravel 中的下拉菜单以显示产品的属性。
<select>
@foreach($attributes as $key=>$attr)
<optgroup label="{{$attr->name}}">
<option value="{{$attr->value}}">{{$attr->value}}</option>
</optgroup>
@endforeach
</select>
当用户存储他可能存储的属性的数据时Color: Red with id=1
和 Color: Blue with id=2
.
用于获取数据的查询是:
$attributes = Attribute::orderBy('name', 'ASC')->get();
不过,我需要根据名称查找类似的记录,例如 Color
. select
下拉列表应列出 $attr->name
曾经在 <optgroup label>
而 $attr->value
应在 <option value>
中重复.
我试图改变查询并使用 groupBy
但这不会像预期的那样工作。查询将只返回任何记录的第一个实例,其余的将被忽略。
$attributes = Attribute::orderBy('name', 'ASC')->groupBy('name')->get();
我该如何解决这个问题?提前谢谢你。
最佳答案
我会将所有属性放入一个多维数组中,然后迭代以生成选择。
// Fetch all attributes
$results = Attribute::orderBy('name', 'ASC')->get();
$attributes = array();
/**
* Group results into a multidimensional array like:
* [color]
* [red]
* [white]
* [shape]
* [circle]
* [square]
*/
foreach ( $results as $v ) {
if ( !isset($attributes[$v->name]) ) {
$attributes[$v->name] = array();
}
$attributes[$v->name][$v->value] = $v->value;
}
// Spit out the select/option groups
?>
<select>
@foreach ( $attributes as $key => $attr )
<optgroup label="{{$key}}">
@foreach ( $attr as $values )
<option value="{{$value}}">{{$value}}</option>
@endforeach
</optgroup>
@endforeach
</select>
关于php - Laravel - 填充选择 optgroup 下拉列表,按名称对记录进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32188712/