// +---------------------------------------------------------------------- declare (strict_types=1); namespace app\store\model; use app\common\library\helper; use app\common\model\Spec as SpecModel; use app\store\model\SpecValue as SpecValueModel; use cores\exception\BaseException; /** * 规格组模型 * Class Spec * @package app\store\model */ class Spec extends SpecModel { /** * 验证规格值是否合法 * @param array $specList * @throws BaseException */ public static function checkSpecData(array $specList) { foreach ($specList as $item) { $values = helper::getArrayColumn($item['valueList'], 'spec_value'); if (count($item['valueList']) != count(array_unique($values))) { throwError('很抱歉,不能存在重复的规格值 请检查您的输入'); } } } /** * 规格组写入数据库并生成id * 此时的$specList是用户端传来的 * @param array $specList * @return array * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException */ public static function getNewSpecList(array $specList): array { // 规格组名称合集 $names = helper::getArrayColumn($specList, 'spec_name'); // 获取到已存在的规格组 $alreadyData = static::getListByNames($names); // 遍历整理新的规格集 foreach ($specList as $key => &$item) { $alreadyItem = helper::getArrayItemByColumn($alreadyData, 'spec_name', $item['spec_name']); if (!empty($alreadyItem)) { // 规格名已存在的记录spec_id $item['spec_id'] = $alreadyItem['spec_id']; } else { // 规格名不存在的新增记录 $result = static::add($item); $item['spec_id'] = $result['spec_id']; } // 规格值写入数据库并生成id $item['valueList'] = SpecValueModel::getNewValueList((int)$item['spec_id'], $item['valueList']); } return $specList; } /** * 新增规格组记录 * @param array $item * @return static|\think\Model */ private static function add(array $item) { // 拿到所有的规格组名称集 // 获取到已存在的 return self::create([ 'spec_name' => $item['spec_name'], 'store_id' => self::$storeId ]); } /** * 根据规格组名称集获取列表 * @param array $names * @return \think\Collection * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException */ private static function getListByNames(array $names): \think\Collection { return (new static)->where('spec_name', 'in', $names)->select(); } }