Laravel将父母的孩子带回同桌 [英] Laravel returning children of parents in same table

查看:109
本文介绍了Laravel将父母的孩子带回同桌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Laravel 5.1,我试图从MySQL类别表创建一个菜单列表。我的服务提供商返回数据,但我不明白如何在foreach循环中创建子类别。当我执行循环时,只返回子查询的最后一行。

Using Laravel 5.1, I am trying to create a menu list from a MySQL categories table. My service provider returns data, but I don't understand how to create the child categories in a foreach loop. When I perform the loop, only the last row of the child query is returned. Any guidance would be appreciated.

类别表

id  | cat_name      | cat_parent_id
--- | --------------| ------------- 
1   | Parent Cat 1  | NULL 
2   | Parent Cat 2  | NULL 
3   | Child Cat 1   | 2 
4   | Child Cat 2   | 2 
5   | Parent Cat 3  | NULL 
6   | Child Cat 3   | 5

所需结果

Parent Cat 1
Parent Cat 2
    Child Cat 1
    Child Cat 2
Parent Cat 3
    Child Cat 3

viewComposerServiceProvider.php

public function boot()
{
       $this->composeTopCategoryNavigation();
       $this->composeSubCategoryNavigation();
}

private function composeTopCategoryNavigation()
{
    view()->composer('partials.header', function($view)
        {
            $view->with('top_cats', Category::whereNull('cat_parent_id')->orderBy('cat_name', 'asc')->get());
        });
}

private function composeSubCategoryNavigation()
{
        view()->composer('partials.header', function($view)
        {
            $view->with('sub_cats', Category::whereNotNull('cat_parent_id')->orderBy('cat_name', 'asc')->get());
        });
}

标题视图

<ul>
@foreach ($top_cats as $top_cat)
  <?php $top_cat_slug = str_slug( $top_cat->cat_name, "-"); ?>
  <li>{{ $top_cat->cat_name }}
    @foreach ($sub_cats as $sub_cat)
            @if ( $sub_cat->cat_parent_id === $top_cat->id )
                <ul>
                  <li{{ $sub_cat->cat_name }}</li>
                </ul>
                @endif
        @endforeach
   </li>
@endforeach
</ul>


推荐答案

首先,你所做的是效率低下。您的视图遍历每个父类别的所有子类别。如果您正确地定义了关系并利用了Eloquent的热切加载,您可以以更简单的方式获取和访问子类别。

First of all, what you are doing is inefficient. Your view iterates through all subcategories for every parent category. If you defined relations properly and made use of Eloquent's eager loading, you could fetch and access child categories in easier way.

从定义关系开始:

class Category extends Model {
  //each category might have one parent
  public function parent() {
    return $this->belongsToOne(static::class, 'cat_parent_id');
  }

  //each category might have multiple children
  public function children() {
    return $this->hasMany(static::class, 'cat_parent_id')->orderBy('cat_name', 'asc');
  }
}

一旦你正确定义了关系,你可以获取整个类树如下:

Once you have the relations defined properly, you can fetch whole category tree like below:

view()->composer('partials.header', function($view) {
  $view->with('categories', Category::with('children')->whereNull('cat_parent_id')->orderBy('cat_name', 'asc')->get());
});

第二个作曲家不需要,因为父类别已经包含孩子。

The second composer won't be needed, as parent categories already contain children.

现在,您只需要在视图中显示类别:

Now, you only need to display the categories in your view:

<ul>
  @foreach ($categories as $parent)
    <li>{{ $parent->cat_name }}
      @if ($parent->children->count())
        <ul>
          @foreach ($parent->children as $child)
            <li>{{ $child->cat_name }}</li>
          @endforeach
        </ul>
      @endif
    </li>
  @endforeach
</ul>

这篇关于Laravel将父母的孩子带回同桌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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