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 = MallCateModel::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); // $models = ($this->category_models); $pid = 0; foreach ($models as $model) { if (!$model->parent_id) { $model->parent_id = $pid; //查找上级分类数据 $goods_cate = MallCateModel::findOne(['and', ['mall_id' => $this->mall_id, 'id' => $pid], ['<>', 'status', StatusEnum::DELETE]]); 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 MallCateModel(); $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['name']) && $category_arr[] = $category_1; !empty($category_2['name']) && $category_arr[] = $category_2; !empty($category_3['name']) && $category_arr[] = $category_3; if (empty($category_arr)) { throw new Exception('供应链返回分类为空'); } // 去除空格 $category_arr = array_map(function ($item) { $item['name'] = str_replace(' ', '', $item['name']); return $item; }, $category_arr); return $category_arr; } }