| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- declare (strict_types = 1);
- namespace app\model\api;
- use think\Model;
- /**
- * @mixin \think\Model
- */
- class StoreCart extends Model
- {
- protected $name = 'store_cart';
- /**
- * 获取购物车列表
- * @param int $uid
- * @return array
- */
- public function getCartList($uid)
- {
- $list = $this->alias('c')
- ->field('c.*,p.title,p.image,p.price as product_price')
- ->leftJoin('store_product p', 'p.id = c.product_id')
- ->where('c.uid', $uid)
- ->select()
- ->toArray();
- return $list;
- }
- /**
- * 添加购物车
- * @param array $data
- * @return int|false 成功返回购物车ID,失败返回false
- */
- public function addToCart($data)
- {
- // 确保cart_num为整数
- $cartNum = (int)($data['cart_num'] ?? 1);
- if ($cartNum <= 0) {
- $cartNum = 1;
- }
-
- // 检查是否已存在
- $exist = $this->where('uid', $data['uid'])
- ->where('product_id', $data['product_id'])
- ->where('product_attr_unique', $data['product_attr_unique'] ?? '')
- ->find();
- if ($exist) {
- // 更新数量,使用整数类型
- $result = $this->where('id', $exist['id'])->inc('cart_num', $cartNum)->update();
- return $result ? $exist['id'] : false;
- } else {
- // 新增
- $data['cart_num'] = $cartNum;
- $result = $this->insert($data);
- return $result ? $this->getLastInsID() : false;
- }
- }
- /**
- * 修改购物车数量
- * @param int $id
- * @param int $cartNum
- * @param int $uid
- * @return bool
- */
- public function updateCartNum($id, $cartNum, $uid)
- {
- return $this->where('id', $id)->where('uid', $uid)->update(['cart_num' => $cartNum]);
- }
- /**
- * 删除购物车
- * @param array $ids
- * @param int $uid
- * @return bool
- */
- public function deleteCart($ids, $uid)
- {
- return $this->where('uid', $uid)->whereIn('id', $ids)->delete();
- }
- }
|