选择具有2个级别的类别(类别和子类别)

时间:2016-12-15 17:47:23

标签: php laravel laravel-5.2

即时创建一个包含2个leves,类别和子类别的选择类别,我已经创建并保存数据库中的数据,唯一缺少的是在视图页面中,使选择字段显示我的期望,但我有如果它有多么可疑,有人会暗示吗?

代码示例:

categories:
- id;
- name;
- parent_id;

example data:
1,  Politics, null;
2, Sports, null;
3, World, null;
4, Soccer, 2;

Final result on Input Select:
Politics
Sports
-- Soccer
World


my view:
<select  name="category" id="category" class="form-control">
                                <option>Select...</option>
                                  @foreach($categories as $category)
                                    <option value="{{$category->id}}">{{$category->name}}</option>

                                  @endforeach
                              </select>

1 个答案:

答案 0 :(得分:3)

categories之间创建一个关系:

类别模型

public function subcategories()
{
    return $this->hasMany('App\Category', 'parent_id');
}

public function parent()
{
    return $this->belongsTo('App\Category');
}

然后您可以将其查询为:

$Categories = Category::whereNull('parent_id')->with('subcategories')->get();

在您看来,您可以这样做:

@foreach($categories as $category)
  <option value="{{$category->id}}">{{$category->name}}</option>
  @foreach($category->subcategories as $subcategory)
    <option value="{{$subcategory->id}}">{{$subcategory->name}}</option>
  @endforeach
@endforeach