发布商品功能-获取分类关联的品牌
在发布商品时,还需要获取当前选择分类的所有品牌,对应前端请求:
对应API文档:
由于返回的数据不是整个品牌表对应的数据,所有新建一个VO来保存返回的信息:
package com.lastingwar.mall.product.vo;
import lombok.Data;
@Data
public class BrandVo {
/**
* "brandId": 0,
* "brandName": "string",
*/
private Long brandId;
private String brandName;
}
来到对应的控制层:/product/categorybrandrelation/brands/list:
/**
* /product/categorybrandrelation/brands/list
*
* 1、Controller:处理请求,接受和校验数据
* 2、Service接受controller传来的数据,进行业务处理
* 3、Controller接受Service处理完的数据,封装页面指定的vo
*/
@GetMapping("/brands/list")
public R relationBrandsList(@RequestParam(value = "catId",required = true)Long catId){
List<BrandEntity> vos = categoryBrandRelationService.getBrandsByCatId(catId);
List<BrandVo> collect = vos.stream().map(item -> {
BrandVo brandVo = new BrandVo();
brandVo.setBrandId(item.getBrandId());
brandVo.setBrandName(item.getName());
return brandVo;
}).collect(Collectors.toList());
return R.ok().put("data",collect);
}
之后创建方法实现方法getBrandsByCatId(catId):
/**
* 通过分类ID查出所以品牌的实体类
* @param catId 分类ID
* @return 所以相关品牌的集合
*/
@Override
public List<BrandEntity> getBrandsByCatId(Long catId) {
List<CategoryBrandRelationEntity> catelogId = relationDao
.selectList(new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", catId));
//使用流做映射把分类ID转化为品牌实体类
List<BrandEntity> collect = catelogId.stream().map(item -> {
Long brandId = item.getBrandId();
BrandEntity byId = brandService.getById(brandId);
return byId;
}).collect(Collectors.toList());
return collect;
}
之后重启服务,来到前端测试,可以看到能够正确显示品牌。