Laravel模型到Bootstrap树视图

时间:2015-10-23 08:57:41

标签: php twitter-bootstrap laravel treeview bootstrap-treeview

基本上我完全被这个问题困扰了。我在Laravel中有一个像这样定义的模型

class BlogCategory extends Model
{
    protected $table = 'blog_categories';

    protected $fillable = [
    'parent_id',
    'title',
    'slug'];

    public function parent()
    {
        return $this->belongsTo('App\Models\BlogCategory','parent_id','blog_category_id');
    }
    public function children()
    {
    return $this->hasMany('App\Models\BlogCategory','blog_category_id','parent_id');
    }
}

现在你可以看到这个模型可以与自己建立父子关系。

现在我正在使用的bootstrap树视图是我的数据格式如下:

var tree = [
        {
            text: "Parent 1",
            nodes: [
                {
                    text: "Child 1",
                    nodes: [
                        {
                            text: "Grandchild 1"
                        },
                        {
                            text: "Grandchild 2"
                        }
                    ]
                },
                {
                    text: "Child 2"
                }
            ]
        },
        {
            text: "Parent 2"
        },
        {
            text: "Parent 3"
        },
        {
            text: "Parent 4"
        },
        {
            text: "Parent 5"
        }
    ];

我如何达到预期的效果?

2 个答案:

答案 0 :(得分:0)

你不必使用关系来制作这棵树。只需选择所有BlogCategory模型并递归迭代它们以制作树。

例如,您可以使用此处的答案Recursive function to generate multidimensional array from database result并根据您的需要采用它。

答案 1 :(得分:0)

我对L-5.2提出了类似的情况,如果你想在多个级别显示类别,其中单个表是为多级别类别维护的,我想这会很有用。

id | category_id | name
1      NULL        Main Category
2       1           -Sub-Category
3       1           -Sub Child
4      Null        Second Main
5       4           -Second Sub

在分类模型中

public function subcategory()
{
    return $this->hasMany(Category::class);
}

然后在Controller中或您需要列出的地方:

$categories = \App\Category::where('category_id', null)->get();

然后,您可以在视图中使用:

<ul>
@foreach($categories as $category)
    <li>{{ $category->name }}
        @if(count( $category->subcategory) > 0 )
            <ul>
            @foreach($category->subcategory as $subcategory)
                <li>{{ $subcategory->name }}</li>
 {{-- If you want upto 3 level, then you can repeat above code with if condition here --}}
            @endforeach 
            </ul>
        @endif
    </li>                   
@endforeach
</ul>

这将在视图中看起来像这样:

  • 主要类别
  • - 子类别
  • - 子孩子
  • Second Main
  • - Second Sub

如果这有用,请告诉我。感谢