1], ]; } 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); $attr = json_encode($attr, JSON_UNESCAPED_UNICODE); $food_flag = FoodFlag::findOne($this->flag_id); $cart = FoodCart::findOne([ 'goods_id' => $this->goods_id, 'user_id' => $this->user_id, 'saas_id' => $this->saas_id, 'is_delete' => 0, 'attr' => $attr, 'flag_id' => $this->flag_id ]); if (!$cart) { $cart = new FoodCart(); $cart->goods_id = $this->goods_id; $cart->user_id = $this->user_id; $cart->saas_id = $this->saas_id; $cart->num = 0; $cart->flag_id = $this->flag_id; $cart->created_at = time(); $cart->is_delete = 0; $cart->attr = $attr; } $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() ]; } } }