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

namespace app\common\model;

use think\Model;

/**
 * @package app\common\model
 * @class Region
 * @author xzncit 2024-02-14
 */
class Region extends Model {

    protected $name = "region";

    /**
     * @param $data
     * @param string $join
     * @return array|string
     */
    public static function getArea($data,$join=''){
        $arr = [];
        foreach ($data as $item){
            $arr[] = self::where(['id' => $item])->value("name");
        }

        if(!empty($join)){
            return implode($join, $arr);
        }

        return $arr;
    }

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

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

        return $res;
    }

    /**
     * @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 getChildren($id,$res=[]){
        $row = self::where(["pid"=>$id])->select()->toArray();
        foreach($row as $val){
            $res[] = $val["id"];
            $res = array_merge($res,self::getChildren($val["id"]));
        }

        return $res;
    }

}