1)需求分析
2)需求分析
Ⅰ 添加购物车
如果该用户买了几个菜品几个套餐,表中就有多条数据
3)代码开发-交互过程
①请求:
菜品:dishid 和 dishflavors
setmealid ,没有口味信息
*前端
*后端
mapper、service略!
*controller
@Autowired
private ShoppingCartService shoppingCartService;
/**
* 添加购物车
* @param shoppingCart
* @return
*/
@PostMapping("/add")
public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
log.info("购物车数据:{}",shoppingCart);
//设置用户id,指定当前是哪个用户的购物车数据,通过 BaseContext.getCurrentId()获取或者session获取
Long currentId = BaseContext.getCurrentId();
shoppingCart.setUserId(currentId);
//查询当前添加的菜品或套餐是否在购物车中,如果是,则数量+=1 (业务场景是,该菜品或套餐多次点击加入购物车)
Long dishId = shoppingCart.getDishId();
LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ShoppingCart::getUserId,currentId);
if(dishId != null){//添加到购物车的是菜品
queryWrapper.eq(ShoppingCart::getDishId,dishId);
}else{//添加到购物车的是套餐
queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
}
//select * from shoppingcart where user_id = ? and dish_id/setmeal_id = ? tips:dish_id/setmeal_id取其一
ShoppingCart shoppingCartOne = shoppingCartService.getOne(queryWrapper);
//如果存在,则数量+=1,再更新之
if(shoppingCartOne != null){
Integer number = shoppingCartOne.getNumber();
shoppingCartOne.setNumber(number + 1);
shoppingCartService.updateById(shoppingCartOne);
}else{
//如果不存在,则添加到购物车,数量默认1
shoppingCart.setNumber(1);
shoppingCart.setCreateTime(LocalDateTime.now());//设置时间
shoppingCartService.save(shoppingCart);
shoppingCartOne = shoppingCart;
}
return R.success(shoppingCartOne);
}
BUG 1:
如果选择了其他口味,则该菜品还是在数量上+1,而不是添加了一条新记录,并且在shoppingcart对应的记录中,也没有更新第一次之后重新选择的菜品的口味
BUG 2:
在选择某套餐加入购物车之后,跑到别的标签页再点击回来时,该套餐没显示数量
Ⅱ 查看购物车
1)前端
*controller
/**
* 查看购物车
* @return
*/
@GetMapping("/list")
public R<List<ShoppingCart>> list(){
log.info("查看购物车……");
LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
//根据userId查询 (用户id在登录时,有设置在该线程中)
queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
//排序
queryWrapper.orderByDesc(ShoppingCart::getCreateTime);
List<ShoppingCart> list = shoppingCartService.list();
return R.success(list);
}
Ⅲ 清空购物车
1)前端
*controller
/**
* 清空购物车
* @return
*/
@DeleteMapping("/clean")
public R<String> clean(){
//delete from shopping_cart where user_id = ?
LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
shoppingCartService.remove(queryWrapper);
return R.success("清空购物车成功");
}