购物车只显示一次商铺,然后在显示该商铺所有加入购物车的商品。 java逻辑怎么写? java逻辑怎么写?

购物车用cookie实现
2025-05-20 03:09:49
推荐回答(1个)
回答(1):

问题不太完整,首先购物车有很多种实现方法.常见的有cookie保存和数据库保存.

其实不管是哪种保存方式,你的问题的本质解决方案其实就是一个数据聚合的过程.我们假设你是用的数据库来保存购物车.你可以把购物车的展示拆解为两个ajax接口.(我只写伪代码).

假设你的购物车表结构如下:

商铺表结构如下:

接口1(用来查看用户购物车里面有哪些商铺):

public List getMyShoppingCartShopList(Integer userId) {
     String sql = "select DISTINCT(shop_id),shop_info.shop_name, count(1) from shopping_cart 
left join shop_info on shop_info.id = shopping_cart.shop_id
where user_id = ? group by shop_id";

     //执行sql,返回数据持久对象,怎么写取决于你用jdbc,mybatis还是其他.
     List cartShopInfoList = cartShopInfoDao.execute(sql,userId);
     return cartShopInfoList;
}

接口2(用来查看用户购物车里商铺的全部商品)

public List getMyShoppingCartProductList(Integer userId,Integer shopId) {
     String sql = "select * from product_info where id in (select product_id from shopping_cart 
     where user_id = ? and shop_id = ?)";
     List productList = productDao.execute(sql,userId,shopId);
     return productList;
}

如果嫌两个接口麻烦,可以把接口逻辑合并,返回一个Map

public class ShopCartInfo {
    private ShopInfo shopInfo;
    private List productList;
    
    //... getter and setter
}