<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\service;

use app\common\model\Category as CategoryModel;

/**
 * @package app\common\service
 * @class Category
 * @author xzncit 2023-09-04
 */
class Category {

    /**
     * 获取上级分类
     * @param $id
     * @param array $res
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getParentList($id,$res=[]){
        $row = CategoryModel::where("id",$id)->find();

        if(!empty($row)){
            $res[] = $row;
            if($row["pid"] != 0){
                $res = array_merge(self::getParentList($row["pid"],$res));
            }
        }

        return $res;
    }

    /**
     * @param $id
     * @param string $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getParentField($id,$field=''){
        $result = self::getParentList($id);

        $array = [];
        foreach($result as $value){
            $array[] = $value[$field];
        }

        return $array;
    }

    /**
     * @param $id
     * @param array $res
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function parent($id,$res=[]){
        $row = CategoryModel::where("id",$id)->find();

        if(!empty($row)){
            $res[] = $row["id"];
            if($row["pid"] != 0){
                $res = array_merge(self::parent($row["pid"],$res));
            }
        }

        return $res;
    }

}