【问题标题】:Convert Eloquent Relationship into array for Form::select()将 Eloquent 关系转换为 Form::select() 的数组
【发布时间】:2013-07-17 11:09:59
【问题描述】:

我希望能够为我的关系生成带有“optgroups”的表单选择。

此代码有效:

        foreach($old_project as $project)
        {
            foreach ($project->units as $unit)
            {
                $new_project[$project->name][] = $unit->name;
            }
        }

那么在我看来:

 {{ Form::select('units', $new_project) }}

但这似乎不对。我尝试做 $old_project->toArray() - 但这也不起作用。

I looked at this forum post - 所以我也尝试过 ->list() - 但我似乎无法让它工作。

在 Laravel 4 中有更好的方法吗?

编辑:

这是我的最终目标 - 类似这样:

<select id="optgroup3" name="unit">
   <optgroup label="Project1">
         <option value="1">Option 1</option>
         <option value="2">Option 2</option>
   </optgroup>
   <optgroup label="Project2">
         <option value="3">Option 3</option>
         <option value="4">Option 4</option>
   </optgroup>
</select>

附言如果可以避免,我不想这样做 - 我想使用 Form::select() 并保持干净:

<select id="optgroup3" name="unit">
       @foreach($units as $project)
             <optgroup label="{{{ $project->name }}}">
                    @foreach($project->units as $unit)
                          <option value="{{{ $unit->id }}}">{{{ $unit->name }}}</option>
                    @endforeach
             </optgroup>
       @endforeach
</select>

【问题讨论】:

  • 您想为每个 optgroup 添加一个标签吗?
  • 是的,我会 - 我已经用更多信息更新了我的问题
  • 你能发布$old_project对象吗?
  • 你有没有找到一个干净的解决方案?
  • 我刚刚做了一个帮助循环的助手——效果很好。我只需要这种形式 - 所以我从来没有真正尝试过......

标签: laravel laravel-4 eloquent


【解决方案1】:

我认为您所使用的命令实际上是 lists()。试试:

Project::lists('name', 'id')

【讨论】:

    猜你喜欢
    • 2015-11-15
    • 2020-01-08
    • 2016-09-14
    • 1970-01-01
    • 2021-01-26
    • 2016-05-24
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    相关资源
    最近更新 更多