laravel递归获取子类所有的父类

laravel获取子类所有的父类

```
public static function allMainId($array,$id){
$array = SalesCatalog::select('id','parent_id')->where('id',$id)->get()->toArray();
$arr = array();
foreach($array as $v){
if($v['id'] == $id){
$arr[] = $v['parent_id'];
$arr = array_merge($arr,self::allMainId($array,$v['parent_id']));
};
};
return $arr;
}
```

表结构如下

```
CREATE TABLE hl_sales_catalog (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
sales_catalog_name varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '销售目录名称',
parent_id bigint(20) NOT NULL COMMENT '父级目录id',
sort mediumint(9) NOT NULL DEFAULT '0' COMMENT '排序:越小越往前排',
created_at timestamp NULL DEFAULT NULL,
updated_at timestamp NULL DEFAULT NULL,
PRIMARY KEY (id) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=111 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;
```

调用方法

`$all_main_id = self::allMainId('',$params['parent_id']);`

    A+
发布日期:2022年09月03日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: