将商品加入购物车
- 数据库中建立一张具有用户id、商品id、商品数量、商品类型的表(其他字段自行扩展)
- 添加商品时先去表中查询该用户的商品是否已存在,存在则将现在需要增加的商品数量加上表中原商品数量,不存在则直接向表中加入数据
获取购物车列表
代码如下
//1.从数据库表中获取该用户所有商品记录
List<Map> cartList = db().selectList("memberCart.getCartList", params);
//2.创建一个map集合,以店铺id为主键,商品信息为值,根据店铺id对商品进行分组
Map<Integer,List<Map>> goodsByMerchantId = new HashMap<>();
//3.创建一个结果集list
List<Map> res = new ArrayList<>();
if(BaseUtil.isNotEmpty(cartList)){
//4.遍历商品记录(注意:购物车表中不能直接存储商品详情,因为商品详情随时都有可能被改动)
for (Map item : cartList) {
item.put("appKey",params.get("appKey"));
item.put("appSecret",params.get("appSecret"));
Map goods = getGoodDetail(item);//获取商品详情
goods.put("cartItemId",item.get("id"));
goods.put("goodsNumber",item.get("goodsNumber"));//将购物车中保存的商品数量放入商品详情
goods.put("siteId",item.get("siteId"));
goods.put("siteName",item.get("siteName"));
Integer merchantId = Integer.valueOf(goods.get("merchantId").toString());//获取该商品的店铺id
//5.从map集合中获取该店铺下的商品列表
//6.如果该列表为空,则需要创建一个空的商品列表,再加入该商品
//7.如果该列表不为空,则直接加入商品
List<Map> list = goodsByMerchantId.get(merchantId);
if(BaseUtil.isEmpty(list)){
list=new ArrayList<>();
list.add(goods);
goodsByMerchantId.put(merchantId,list);
}else {
list.add(goods);
}
}
//8.遍历map集合,构造结果集list,以便前端循环显示
//9.list中每一个map表示一个店铺(店铺中有多个商品)
for (Integer merchantId : goodsByMerchantId.keySet()) {
Map map = new HashMap<>();
map.put("merchantId",merchantId);
map.put("merchantName",getMerchantById(merchantId).get("merchantName"));
map.put("goodsList",goodsByMerchantId.get(merchantId));
res.add(map);
}
}
//返回结果集list
return res;
购物车列表显示效果,如下图