【问题标题】:Laravel : Get main level category on a tree parent child relationshipLaravel:获取树父子关系的主要级别类别
【发布时间】:2020-08-03 16:55:16
【问题描述】:

我有一个多级类别模型,每个类别可以在同一个 sql 表上的同一个表(树结构)上有子级和父级。

public function childs(){
return $this->hasMany('App\Category', 'parent_id', 'id');
}

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

+---------+---------+------------+
| id      |cat_name | parent_id  | 
+---------+---------+------------+
|       1 |     A   | NULL       |
|       2 |     B   | NULL       |
|       3 |     AA  | 1          |
|       4 |     BB  | 2          |
|       5 |     AAA | 4          |
+---------+---------+------------+

我想从我的控制器中获取所有类别及其主类别(不是父类别),如下所示:

 $categories= Category::with('mainCategory')->get();

想要的结果

id: 1
cat_name: A
parent_id:null
mainCategory:{}

id: 2
cat_name: B
parent_id:null
mainCategory:{}

id: 3
cat_name: AA
parent_id:1
mainCategory:{
             id: 1
             cat_name: A
             parent_id:NULL
             }

id: 4
cat_name: BB
parent_id:2
mainCategory:{
             id: 2
             cat_name: B
             parent_id:NULL
             }


id: 5
cat_name: AAA
parent_id:3
mainCategory:{
             id: 1
             cat_name: AAA
             parent_id:NULL
             }

例如:id 为 5 的类别 AAA -> mainCat 是 A

我需要一个模型函数,它为每个类别返回类别和 mainCategory,因此我可以从另一个控制器而不是 CategoryController 应用该函数。

【问题讨论】:

  • 为父类和子类创建两个表,你可以轻松使用hasMany
  • 感谢您的回复,但我认为您没有很好地回答问题。

标签: laravel nested treeview parent-child eloquent-relationship


【解决方案1】:

我明白你的问题。

为父子类创建两张表,因为父类有很多子类

示例表

标记父类别

id, name

表格子类别

id, parent_category_id

同时创建两个模型

ParentCategoryModel

public function childs(){ return $this->hasMany(ChildCategoryModel::class, 'parent_category_id', 'id'); }

ChildCategoryModel

public function parent(){ return $this->belongsTo(ParentCategoryModel::class,'parent_category_id')->withDefault(); }

在你的控制器中,你可以像这样使用 eloquent categories=ChildCategoryModel::with('parent')->get();

【讨论】:

  • 感谢 Encang,但您不需要两张表,一张带有外国 ID 的表可以给出相同的结果,此外,我得到孩子没有任何问题,我想要的是递归获取 N 级子级的顶级父级。
猜你喜欢
  • 1970-01-01
  • 2020-12-08
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多