yii2 获取父类下所有子类的数据查询

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lyb8010/article/details/88382873

Controller.php

$cid = Yii::$app->request->get("id");

$cat = new BieshuCat();
$data = $cat->getData();
$allcat = $cat->getTree($data,$cid);

$catarr = array_reduce($allcat , function($result , $v){
            return $result.','.$v['id'];
        });

$catarr = explode(",",$cid.$catarr);

$model = Bieshu::find()->where(['in','cat_id',$catarr]);

Model.php

 public function getData($status = 1)
    {
        if( $status > ConstantMapService::$status_default ){
            $cates = self::find()->where([ 'status' => $status ])->all();
        }else{
            $cates = self::find()->all();
        }
        $cates = ArrayHelper::toArray($cates);
        return $cates;
    }

    public function getTree($cates, $pid = 0)
    {
        $tree = [];
        foreach($cates as $cate) {
            if ($cate['parentid'] == $pid) {
                $tree[] = $cate;
                $tree = array_merge($tree, $this->getTree($cates, $cate['id']));
            }
        }
        return $tree;
    }

猜你喜欢

转载自blog.csdn.net/lyb8010/article/details/88382873