【问题标题】:how can i show my subcategories with parent and children relation我怎样才能显示我的子类别与父母和孩子的关系
【发布时间】:2021-06-15 15:45:48
【问题描述】:

我有category 表,它有一个带有两个值的parent_id 列:childrenparent

parent_id 为 NULL 时,它是父(类别),否则它是子(子类别)。

更多细节:我有一个navigation blade,我在其中显示类别并在下拉列表中显示子类别。我在我的刀片中扩展了它。所以当您在控制器中看到 $nav_category 变量时,它用于在导航中显示类别

当我单击一个类别并打开其页面时,我希望能够看到它的 subcategories 但它向我显示了所有 subcategories

这是我的类别模型:

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
         'parent_id','title' , 'description', 'status',
    ];

    public function parent()
    {
    return $this->belongsTo(Category::class);
    }


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

}

我的 ShowCategoryController :

 public function index($id)
    {

        //all parent categories
        $parent_categories = Category::with('children')->whereNull('parent_id')->get();


        //show categories in navigation
        $nav_categories = $parent_categories->take(7);


        //show categories details (subcategories , posts and tags)
        $show_categories = $parent_categories->find($id)->get();


        return view('home.showcategory' , compact('show_categories' , 'nav_categories'));
    }

显示类别刀片:

@extends('home.mainlayout')

@section('content')

@foreach($show_categories as $show_category)

@foreach($show_category->children as $child)
<div>
   <h2 style="text-align: center">{{ $child->title }}</h2>
</div>
@endforeach
@endforeach
@endsection

导航刀片:

 @foreach($nav_categories as $nav_category)
    <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#"> {{ $nav_category->title }} <span class="caret"></span></a>
        <ul class="dropdown-menu" >
          @foreach($nav_category->children as $child)
             <li><a href="#">{{ $child->title }}</a></li>
          @endforeach
          <li><a href="{{ route('show_category' , $nav_category->id)  }}">more</a></li>
        </ul>
      </li>
    @endforeach

和家庭控制器:

public function index()
    {

        //for show categories in nvaigation
        $nav_categories = Category::with(['children' => function($q) { $q->take(7); }])
        ->whereNull('parent_id')->get();


        return view('home.home' , compact('nav_categories' ));
    }

谢谢你的帮助:)

【问题讨论】:

  • 我认为this 对你有用;)

标签: php laravel parent-child laravel-blade laravel-models


【解决方案1】:

我不清楚您正在使用的确切代码。 尝试将模型中的父方法更改为

 public function parent()
    {
    return (new static)::whereNull('parent_id')->get();
    }

并相应地重新排列控制器。 现在,您的控制器在 $parent_category 和 $show_categories 中两次从模型中获取几乎相同的数据。可能会导致 n+1 查询问题。希望我的想法是对的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多