• 使用 Laravel Eloquent 的 hasMany 来开发无限极分类


    在网上商城上,我们经常可以看到多级分类、子分类、甚至无限极分类。本文将向你展示如何优雅的通过 Laravel Eloquent 将其实现。

     

    我们会创建一个微型项目来展示儿童商店的分类,总共有 5 级,如下:

    数据库迁移

    简单的数据表结构:

    Schema::create('categories', function (Blueprint $table) {
     $table->bigIncrements('id');
     $table->string('name');
     $table->unsignedBigInteger('category_id')->nullable();
     $table->foreign('category_id')->references('id')->on('categories');
     $table->timestamps();
    });

    只有一个 name 字段, 关联到其自身。所以,大部分父级分类 category_id = NULL,每一个子分类都有一个 parent_id

    数据表数据如下:

    Eloquent 模型和关联关系

    首先,在 app/Category.php 创建一个简单的 hasMany() 方法, 分类可能拥有其自分类:

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

      

    好戏开场 本文最妙 “计策”。你知道可以向这样描述 递归 关系吗?如下:

    public function childrenCategories()
    {
     return $this->hasMany(Category::class)->with('categories');
    }
    

      

    因此,如果调用 Category::with(‘categories’),将得到下级 “子分类”,但是通过 Category::with(‘childrenCategories’) 将能帮你实现无限极。

    路由和控制器方法

    现在,让我们尝试显示所有类别和子类别,如上例所示。

    在 routes/web.php,我们添加以下内容:

    Route::get('categories', 'CategoryController@index');
    

      

    app/Http/CategoryController.php 如下所示:

    public function index()
    {
     $categories = Category::whereNull('category_id')
     ->with('childrenCategories')
     ->get();
     return view('categories', compact('categories'));
    }
    

      

    我们仅加载父类别,将子类别作为关系。简单吧?

    视图和递归子视图

    最后,渲染到页面。 在 resources/views/categories.blade.php 文件:

    <ul>
     @foreach ($categories as $category)
     <li>{{ $category->name }}</li>
     <ul>
     @foreach ($category->childrenCategories as $childCategory)
     @include('child_category', ['child_category' => $childCategory])
     @endforeach
     </ul>
     @endforeach
    </ul>
    

      

    我们先遍历了最顶级的父类别,然后遍历出父类的子类别,然后使用 @include 加载子类别的子类别......

    最好的部分是 resources/views/admin/child_category.blade.php 将使用递归加载自身。看代码:

    <li>{{ $child_category->name }}</li>
    @if ($child_category->categories)
     <ul>
     @foreach ($child_category->categories as $childCategory)
     @include('child_category', ['child_category' => $childCategory])
     @endforeach
     </ul>
    @endif
    

      

    在 child_category.blade.php 内部,我们包含了 @include(‘child_category’),因此只要当前子类别中有类别,模板就会递归地加载子类别。

    就是这样!我们拥有无限级别的子类别 - 无论是在数据库还是关联关系或是视图中

    更多学习内容请访问:

    腾讯T3-T4标准精品PHP架构师教程目录大全,只要你看完保证薪资上升一个台阶(持续更新)图标

  • 相关阅读:
    Rancher之Pipeline JAVA demo
    rancher使用fluentd-pilot收集日志分享
    SFTP 命令列表以备查询
    WPF中异步更新UI元素
    Android 开发环境在 Windows7 下的部署安装
    Android Studio vs. Eclipse ADT Comparison
    JQuery 滚动条插件perfect-scrollbar
    nginx+php 在windows下的简单配置安装
    MySql 管理操作常用命令
    JS事件调试
  • 原文地址:https://www.cnblogs.com/a609251438/p/12868914.html
Copyright © 2020-2023  润新知