如何在Laravel中创建类别的嵌套列表? [英] How to create a nested-list of categories in Laravel?

查看:56
本文介绍了如何在Laravel中创建类别的嵌套列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Laravel中创建类别的嵌套列表?

How can I create a nested list of categories in Laravel?

我想创建类似这样的东西:

I want to create something like this:

  • --- Php
  • ------ Laravel
  • ---------版本
  • ------------ V 5.7
  • --- Python
  • ------ Django
  • --- Ruby
  • ..........
  • --- Php
  • ------ Laravel
  • --------- Version
  • ------------ V 5.7
  • --- Python
  • ------ Django
  • --- Ruby
  • ..........

我的类别表的字段是:

id | name | parent_id

如果我必须添加另一列(例如深度或其他内容),请告诉我.

If I have to add another column like depth or something, please tell me.

我正在使用以下代码,但我认为这不是最佳解决方案.此外,我无法将此功能传递给我的视图.

I am using this following code, but I think it is not the best solution. Besides, I can not pass this function to my view.

function rec($id)
{
     $model = Category::find($id);
     foreach ($model->children as $chield) rec($chield->id);
     return $model->all();
}

function main () {
    $models = Category::whereNull('parent_id')->get();
    foreach ($models as $parent) return rec($parent->id);
}

推荐答案

您可以创建自引用模型:

You can make a self-referential model:

class Category extends Model {

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

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

并建立递归关系:

// recursive, loads all descendants
public function childrenRecursive()
{
   return $this->children()->with('childrenRecursive');
}

并让所有子女与父母同住

and to get parents with all their children:

$categories = Category::with('childrenRecursive')->whereNull('parent')->get();

最后,您只需要遍历子代直到子代为空.如果您不小心,肯定会出现一些性能问题.如果您打算保留这样一个很小的数据集,那应该不成问题.如果这将成为一个不断增长的列表,那么可能有一个root_parent_id或要查询的内容并手动组装该树可能很有意义.

Lastly you need to just iterate through the children until children is null. There can definitely be some performance issues with this if you are not careful. If this is a fairly small dataset that you plan to remain that way it shouldn't be an issue. If this is going to be an ever growing list it might make sense to have a root_parent_id or something to query off of and assemble the tree manually.

这篇关于如何在Laravel中创建类别的嵌套列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆