1], [['food_ext_goods'], 'safe'], ]; } public function save() { try { if (!$this->validate()) { return [ 'code' => 1, 'msg' => $this->getErrorSummary(false)[0] ]; } $goods = Goods::findOne([ 'id' => $this->goods_id, 'store_id' => $this->store_id, 'is_delete' => 0, 'status' => 1, ]); if (!$goods) { return [ 'code' => 1, 'msg' => '商品不存在或已下架', ]; } $this->attr = json_decode($this->attr, true); $attr = []; foreach ($this->attr as $item) { if (!empty($item['attr_id'])) { $attr[] = intval($item['attr_id']); } } sort($attr); if ($goods->use_attr) { $attrs = $goods->attr; if (!empty($attrs)) { $attrs = json_decode($attrs, true); foreach ($attrs as $item) { $attr_list = array_column($item['attr_list'], 'attr_id'); sort($attr_list); if (!array_diff($attr_list, $attr)) { if ($item['num'] <= 0) { return [ 'code' => 1, 'msg' => '商品规格数量不足', ]; } } } } } $attr = json_encode($attr, JSON_UNESCAPED_UNICODE); $this->food_ext_goods = (array)json_decode($this->food_ext_goods, true); $food_ext_goods = json_encode($this->food_ext_goods, JSON_UNESCAPED_UNICODE); $food_flag = FoodFlag::findOne($this->flag_id); $cart = FoodCart::findOne([ 'goods_id' => $this->goods_id, 'user_id' => $this->user_id, 'is_delete' => 0, 'attr' => $attr, 'food_ext_goods' => $food_ext_goods, 'flag_id' => $this->flag_id ]); if (!$cart) { $cart = new FoodCart(); $cart->goods_id = $this->goods_id; $cart->user_id = $this->user_id; $cart->num = 0; $cart->flag_id = $this->flag_id; $cart->created_at = time(); $cart->is_delete = 0; $cart->attr = $attr; $cart->food_ext_goods = $food_ext_goods; } $cart->status = 1; if ($food_flag->user_id == $this->user_id || $food_flag->type == 1) { $cart->status = 1; } $cart->num += $this->num; $cart_num = FoodCart::find()->where(['flag_id' => $this->flag_id, 'goods_id' => $this->goods_id, 'is_delete' => 0])->sum('num'); if (($cart_num + $cart->num) > $goods->goods_num) { return [ 'code' => 1, 'msg' => '库存不足', ]; } if ($cart->save()) { return [ 'code' => 0, 'msg' => '添加购物车成功', 'data' => [ 'flag_id' => $this->flag_id ], ]; } else { return ['code' => 1, 'msg' => $cart->errors]; } } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage() . 'line=' . $e->getLine() ]; } } }