我正在使用此查询来获取每个类别的子项
$this['children'] = Cat::first()->children;
但它只获得第一类的子类别,并且所有其他类别都显示相同的子类别。关于如何解决这个问题的任何想法?
模型关系
public function children(){
return $this->hasMany(static::class,'parent_id','id');
表结构
类别表
ID
cat_title
PARENT_ID
nest_right
nest_left
nest_depth
金属块
parent_id = 0(类别)
parent_id> 0(子类别)
要获取每个类别的子类别,首先需要获取每个类别的ID并在查询中使用它。 (例如在foreach循环中)
$this['children'] = Cat::find($id)->children;
如果您需要同时获取所有类别及其相关子类别,您需要急切加载:
$allCatsWithTheirChildren = Cat::with('children')->all();