我的laravel应用程序中有两个带有关联模型的表:subsectors
和sectors
。下面是一个例子。
子类别:
|id | name |sector_id|
|---|---------------|---------|
| 1 | Global Equity | 1 |
| 2 | US Equity | 1 |
| 3 | UK Equity | 1 |
| 4 | Govt Bonds | 2 |
| 5 | IG Bonds | 2 |
| 6 | HY Bonds | 2 |
| 7 | Gold | 3 |
行业:
| id | name |
|----|-------------|
| 1 | Equity |
| 2 | Bonds |
| 3 | Commodities |
因此,每个分部门都映射到一个部门。这反映在我的模型类中。
我想为具有选项组的子部门创建一个选择框,其中以部门名称作为选项组名称,以子部门作为选项。对于Laravel的表单生成器,我相信使用了以下语法:
{{ Form::select('subsector', array(
'Equity' => [1 => 'Global Equity', 2 => 'US Equity', 3 => 'UK Equity'],
'Bonds' => [4 => 'Govt Bonds', 5 => 'IG Bonds', 6 => 'HY Bonds'],
//etc...
))}}
我的问题是编写雄辩或流畅的查询,以生成上面要传递给formbuilder的嵌套数组。我想我可以通过循环遍历Eloquent查询结果对象来实现,但我想知道是否有更好的方法来获得2个联接表的简单嵌套结果。
我所有的关系都在模型中定义。
编辑
这个方法有效,但我希望有一个更干净的方法,没有嵌套的for
循环。
$subsectors = [];
$sectors = Sector::with('subsector')->get();
foreach ($sectors as $sector)
{
$subsectors[$sector->name] = [];
foreach ($sector->subsector as $subsector)
{
$subsectors[$sector->name][$subsector->id] = $subsector->name;
}
}
使用Form::macro
,这样就可以做到这一点(我假设subsectors
关系,因为它对hasMany
更准确):
$sectors = Sector::with('subsectors')->get();
Form::groupSelect('subsector', $sectors, 'subsectors')
下面是您需要的宏:
Form::macro(
'groupSelect',
function ($name, $collection, $relation, $groupName = 'name', $optName = 'name', $optValue = 'id', $selected = null, $attributes = [])
{
$groups = [];
foreach ($collection as $model)
{
$groups[$model->$groupName] = $model->$relation->lists($optName, $optValue);
}
return Form::select($name, $groups, $selected, $attributes);
}
);
我建议在您的视图中直接编写HTML标记,而不是在Controller中制定复杂的数组
<select name="subsector">
@foreach(Sector::with('subsector')->get() as $sector)
<optgroup label="{{ $sector->name }}">
@foreach($sector->subsector as $subsector)
<option value="{{ $subsector->id }}">{{{ $subsector->name }}}</option>
@endforeach
@endforeach
</select>