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

我想创造这样的东西:

  • --- Php
  • ------拉维尔
  • --------- Version
  • ------------ V 5.7
  • --- Python
  • ------德扬戈
  • --- Ruby
  • .

The fields of my categories table are:

id | name | parent_id

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

我正在使用以下代码,但我认为这不是最好的解决方案.此外,我不能把这个功能放在我的观点上.

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

and make a recursive relation:

// 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_id')->get();

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相关问答推荐

Laravel 数据未传递到下拉框

Laravel 9:AWS S3 检索要流式传输的视频

当使用Laravel eloquent查询100000条数据时速度很慢

如何在 Laravel 4 中使用没有 id 的 Eloquent 更新数据

Laravel 5 - ErrorException 无法打开流:权限被拒绝

我怎样才能了解更多关于我的 Laravel 排队作业(job)失败的原因?

静态密码在默认的 Laravel 用户工厂中是如何工作的?

Laravel Request::input 调用未定义的方法

在 laravel 中更改时区

Laravel Blade 没有额外的空格?

如何在没有 Eloquent 的情况下创建 Laravel 模型?

如何在 Laravel 4 中使用 SHA1 加密而不是 BCrypt?

Laravel:验证 json 对象

Laravel 的 toSql() 方法是否会屏蔽 id? (列值被问号替换)

Laravel Eloquent 查询生成器默认 Where 条件

如何在 Laravel 中正确安装软件包?

Laravel Eloquent 多态一对一?

Laravel php artisan 产生错误

如何获取 Laravel 块的返回值?

在哪里放置 Blade::extend