$item) { $newAttr[$k] = $item; } foreach ($newAttr as $k => $item) { foreach ($item['attr_list'] as $k2 => $item2) { $attr = Attr::find()->where(['id' => $item2['attr_id'], 'is_delete' => 0])->asArray()->one(); $cache_key = 'attr_group_by_attr_' . $attr['attr_group_id']; $attrGroup = \Yii::$app->cache->get($cache_key); if (!$attrGroup) { $attrGroup = AttrGroup::find()->where(['id' => $attr['attr_group_id'], 'store_id' => $storeId])->asArray()->one(); \Yii::$app->cache->set($cache_key, $attrGroup, 1); } $newAttr[$k]['attr_list'][$k2]['attr_group_name'] = $attrGroup['attr_group_name']; } } return $newAttr; } /** * 商品库存减少 * @param $attrIdList * @param $num * @param array $otherData * @return array */ public static function num($attrIdList, $num, $otherData = []) { try { if (!isset($otherData['action_type']) || !in_array($otherData['action_type'], ['add', 'sub'])) { return [ 'code' => 1, 'msg' => '请传入操作类型action_type, 必须[add||sub]' ]; } $goodId = $otherData['good_id']; switch ($otherData['good_type']) { case 'STORE': $good = Goods::findOne($goodId); break; default: return [ 'code' => 1, 'msg' => '无此商品类型' ]; break; } sort($attrIdList); $attrs = json_decode($good->attr); $subAttrNum = false; foreach ($attrs as $i => $attr) { $goodAttrIdList = []; foreach ($attr->attr_list as $item) { array_push($goodAttrIdList, $item->attr_id); } sort($goodAttrIdList); if (!array_diff($attrIdList, $goodAttrIdList)) { if ($num > intval($attrs[$i]->num)) { return [ 'code' => 1, 'msg' => '商品库存不足,无法购买', ]; } if ($otherData['action_type'] === 'add') { $attrs[$i]->num = intval($attrs[$i]->num) + $num; } if ($otherData['action_type'] === 'sub') { $attrs[$i]->num = intval($attrs[$i]->num) - $num; } $subAttrNum = true; break; } } if (!$subAttrNum) { return [ 'code' => 1, 'msg' => '商品规格信息有误,请检查商品' ]; } $good->attr = Json::encode($attrs, JSON_UNESCAPED_UNICODE); $isTrue = true; if (!$good->save()) { $isTrue = false; } if ($isTrue) { return [ 'code' => 0, 'msg' => '库存充足,可以购买' ]; } return [ 'code' => 1, 'msg' => '服务器出错啦!' ]; } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage(), ]; } } }