Php LAVEL从联接表创建嵌套选择框
在我的laravel应用程序中,我有两个带有关联模型的表:Php LAVEL从联接表创建嵌套选择框,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,在我的laravel应用程序中,我有两个带有关联模型的表:子部门和部门。这里有一个例子 界别分组: |id | name |sector_id| |---|---------------|---------| | 1 | Global Equity | 1 | | 2 | US Equity | 1 | | 3 | UK Equity | 1 | | 4 | Govt Bonds | 2 | | 5 | IG
子部门
和部门
。这里有一个例子
界别分组:
|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 builder,我相信使用了以下语法:
{{ 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。我想我可以通过循环一个有说服力的查询结果对象来实现这一点,但我想知道是否有更好的方法来获得两个联接表的简单嵌套结果
我的所有关系都在模型中定义
编辑
这种方法很有效,但我希望能找到一种更干净的方法,而不必嵌套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
可以这样做(我假设子部门
关系,因为它对于有许多
更准确):
下面是您需要的宏:
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>
@foreach(扇区::with('subsector')->get()作为$Sector)
@foreach($sector->subsector作为$subsector)
{{{$subsector->name}}
@endforeach
@endforeach
为什么这是个好主意?它会导致更多静态混乱的代码,不支持模型表单填充,也不消除嵌套for循环的需要。
<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>