explodeCategory($info['category_id']); // 使用名字 $category_arr = $this->getCategoryName($category_1, $category_2, $category_3); // 倒转 $category_arr = array_reverse($category_arr); foreach ($category_arr as $category) { $category_id = $this->checkCategory($category); // 如果返回分类ID 不继续 if ($category_id) { return $category_id; } // 查询到父类 结束 if ($this->category_end) { break; } } // 没有返回ID, 需要创建 return $this->createCategory(); } /** * 使用名称 * * @param string $category * @return void */ private function checkCategory($category) { // 只查询第一个分类,第一个没有则创建全部 // if ($this->first_category) { $params = [ 'mall_id' => $this->mall_id, // 'is_delete' => 0, 'mch_id' => 0, 'status' => 1, ]; $category_model = MallCate::find()->where($params)->andWhere(['like', 'name', $category['name']])->one(); // 查询到并且是子分类返回 if (!empty($category_model) && $this->first_category) { return $category_model->id; } $this->first_category = false; // } // 父级分类 $pid = !empty($category_model) ? $category_model->id : 0; $this->setCategoryForm($category['name'], $pid); } /** * 创建分类并返回分类ID * * @return int */ public function createCategory() { // 倒序, 从子分类开始加 $models = array_reverse($this->category_models); $pid = 0; foreach ($models as $model) { if (!$model->parent_id) { $model->parent_id = $pid; //查找上级数据 $goods_cate = MallCate::find()->where(['mall_id' => $this->mall_id, 'parent_id' => $pid])->andWhere(['<>', 'status', StatusEnum::DELETE])->asArray()->one(); if (!empty($goods_cate)) $model->level = $goods_cate['level'] + 1; } else { $model->level = 1; } // 保存 $model->save(); $pid = $model->id; } return $pid; } /** * 创建分类model * * @param string $title * @return void */ private function setCategoryForm($title, $pid) { if ($pid) { $level = $this->category_level - 1; $this->category_models[$level]->parent_id = $pid; $this->category_end = true; return; } $model = new MallCate(); $model->mall_id = $this->mall_id; $model->mch_id = 0; // $model->store_id = 0; $model->name = $title; $model->sort = 100; $model->pic = ''; $model->big_pic = ''; $model->advert_pic = ''; $model->advert_url = ''; $model->status = 1; $model->is_show = 1; $model->advert_open_type = ''; $model->advert_params = ''; $model->parent_id = $pid; $model->level = 0; $this->category_models[$this->category_level] = $model; $this->category_level++; } /** * 获取分类 * * @param string $str * @return array */ private function getCategoryName($category_1, $category_2, $category_3) { !empty($category_1) && $category_arr[] = ['name' => Category::getCategoryName($category_1)]; !empty($category_2) && $category_arr[] = ['name' => Category::getCategoryName($category_2)]; !empty($category_3) && $category_arr[] = ['name' => Category::getCategoryName($category_3)]; if (empty($category_arr)) { throw new Exception('供应链返回分类为空'); } return $category_arr; } }