2014-09-24 31 views
0

我在我的laravel应用程序中有两个关联模型表:subsectorssectors。这是一个例子。Laravel从连接表创建嵌套选择框

界别分组:

|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; 
    } 
} 

回答

0

使用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); 
    } 
); 
-2

我不建议在Controller中编写复杂的数组,而是直接编写HTML标记

<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> 
+0

为什么这是个好主意?它会导致更多的静态代码,并且不支持模型表单填充,并且不会消除嵌套for循环的需要。 – harryg 2014-09-24 10:49:08