【谷粒商城基础篇】商品服务开发:属性分组、平台属性

在这里插入图片描述

谷粒商城笔记合集

分布式基础篇分布式高级篇高可用集群篇
===简介&环境搭建===
项目简介与分布式概念(第一、二章)
基础环境搭建(第三章)
===整合SpringCloud===
整合SpringCloud、SpringCloud alibaba(第四、五章)
===前端知识===
前端开发基础知识(第六章)
===商品服务开发===
商品服务开发:基础概念、三级分类(第七、八章)
商品服务开发:品牌管理(第九章)
商品服务开发:属性分组、平台属性(第十、十一章)
商品服务:商品维护(第十二、十三章)
===仓储服务开发===
仓储服务:仓库维护(第十四章)
基础篇总结(第十五章)

十、商品服务&平台属性&属性分组

10.1 前端开发:整合树形组件

在这里插入图片描述

  1. 使用 sql 脚本 创建管理系统的所有目录和菜单

  2. 创建 属性分组组件、树形公共组件

    • 树形公共组件:views/modules/common/category.vue

      <template>
        <el-tree :data="menus" :props="defaultProps" node-key="catId" :default-expanded-keys="expandedKey" ref="menuTree" @node-click="nodeclick">
            <span class="custom-tree-node" slot-scope="{ node }">
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
      </template>
      
      <script>
      export default {
        data () {
          return {
            menus: [],
            expandedKey: [], // 默认展开的分类
            defaultProps: {
              children: 'children',
              label: 'name'
            }
          }
        }
        methods: {
          nodeclick (data, node, component) {
            console.log('子组件产生点击事件', data, node, component)
            // 向父组件传递事件
            this.$emit('tree-node-click', data, node, component)
          },
          getMenus () {
            this.$http({
              url: this.$http.adornUrl('/product/category/list/tree'),
              method: 'get'
            }).then(({data}) => {
              this.menus = data.data
            })
          }
        },
        // 生命周期 - 创建完成(可以访问当前 this 实例)
        created () {
          this.getMenus()
        }
      }
      </script>
      
    • 树形分组组件整合树形组件:views/modules/product/attrgroup.vue

      <template>
        <el-row :gutter="20">
        <el-col :span="6">
          <category @tree-node-click="treenodeclick"></category>
        </el-col>
        <el-col :span="18">
          <!-- 引入renren-generator 生成的增删改组件 -->
        </el-col>
      </el-row>
      </template>
      
      <script>
      import Category from '../common/category.vue'
      import AddOrUpdate from './attrgroup-add-or-update'
      
      export default {
        // import 引入的组件需要注入到对象中才能使用
        components: {Category, AddOrUpdate}
      }
      </script>
      

10.2 前后端联调:查询 分类&模糊匹配💡

在这里插入图片描述

API

  1. AttrGroupController

    /**
     * 列表:三级分类+模糊查询
     */
    @RequestMapping("/list/{catelogId}")
    public R list(@RequestParam Map<String, Object> params,@PathVariable(name = "catelogId") Long catelogId){
        PageUtils page = attrGroupService.queryPage(params,catelogId);
    
        return R.ok().put("page", page);
    }
    
  2. AttrGroupService

    /**
     * 列表:三级分类+模糊查询
     */
    PageUtils queryPage(Map<String, Object> params, Long catelogId);
    
  3. AttrGroupServiceImpl

    /**
     * 列表:三级分类+模糊查询
     * catelogId=0:查询所有
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        // catelogId=0:查询所有
        if(catelogId.equals(0l)){
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    new QueryWrapper<AttrGroupEntity>()
            );
            return new PageUtils(page);
        }else {
            // 获取模糊查询参数
            String key = (String) params.get("key");
            // 1.三级分类
            if(StringUtils.isNullOrEmpty(key)){
                IPage<AttrGroupEntity> page = this.page(
                        new Query<AttrGroupEntity>().getPage(params),
                        new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogId)
                );
                return new PageUtils(page);
            }
            // 2.三级分类+模糊查询
            else{
                IPage<AttrGroupEntity> page = this.page(
                        new Query<AttrGroupEntity>().getPage(params),
                        new QueryWrapper<AttrGroupEntity>()
                                .eq("catelog_id",catelogId)
                                .and(obj->{
                                    obj.eq("attr_group_id",key).or().like("attr_group_name",key);
                                })
                );
                return new PageUtils(page);
            }
        }
    }
    

前端

components/upload/attrgroup.vue:

<script>
export default {
  data () {
    return {
      Cid: 0,
      ...
    }
  },
  methods: {
    treenodeclick (data, node, component) {
      console.log('接收子组件的事件', data, node, component)
      //1.点击分类时保存分类id
      this.Cid = data.catId
      //2.点击三级分类时获取属性分组数据
      if (node.level === 3) {
        this.getDataList()
      }
    },
    getDataList () {
      this.dataListLoading = true
      this.$http({
        //3.修改请求路径
        url: this.$http.adornUrl(`/product/attrgroup/list/${this.Cid}`),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'key': this.dataForm.key
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    }
  }
}
</script>

10.3 前后端联调:新增 分类级联选择器💡

在这里插入图片描述

后端

  • CategoryEntity

    public class CategoryEntity implements Serializable {
    	/**
    	 * 子分类
    	 */
    	@JsonInclude(JsonInclude.Include.NON_EMPTY) //为空的时候不返回此字段
    	@TableField(exist = false)
    	private List<CategoryEntity> children;
    }
    

前端

  1. 引入新增&修改 弹窗组件:components/upload/attrgroup-add-or-update.vue

  2. 将 所属分类输入框 替换为 级联选择器:components/upload/attrgroup-add-or-update.vue

    <template>
      <el-dialog
        :title="!dataForm.attrGroupId ? '新增' : '修改'"
        :close-on-click-modal="false"
        :visible.sync="visible">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
        <el-form-item label="所属分类id" prop="catelogId">
          <!-- 1.替换为级联选择器 -->
          <el-cascader v-model="dataForm.catelogPath" :options="categorys"  :props="props"></el-cascader>
        </el-form-item>
        </el-form>
      </el-dialog>
    </template>
    
    <script>
      export default {
        data () {
          return {
            <!-- 2.自定义选择器使用的数据属性 -->
            props: {
              value: 'catId',
              label: 'name',
              children: 'children'
            },
            <!-- 3.存储分类数据 -->
            categorys: [],
            dataForm: {
              attrGroupId: 0,
              attrGroupName: '',
              sort: '',
              descript: '',
              icon: '',
              <!-- 4.存储选择结果数组 -->
              catelogPath: [],
              <!-- 5.存储分组所属分类 -->
              catelogId: 0
            }
          }
        },
        methods: {
          <!-- 6.获取分类数据 -->
          getCategorys () {
            this.$http({
              url: this.$http.adornUrl('/product/category/list/tree'),
              method: 'get'
            }).then(({ data }) => {
              this.categorys = data.data
            })
          },
          dataFormSubmit () {
            this.$refs['dataForm'].validate((valid) => {
              if (valid) {
                this.$http({
                  url: this.$http.adornUrl(`/product/attrgroup/${!this.dataForm.attrGroupId ? 'save' : 'update'}`),
                  method: 'post',
                  data: this.$http.adornData({
                    'attrGroupId': this.dataForm.attrGroupId || undefined,
                    'attrGroupName': this.dataForm.attrGroupName,
                    'sort': this.dataForm.sort,
                    'descript': this.dataForm.descript,
                    'icon': this.dataForm.icon,
                    <!-- 7.获取存储分组所属分类 -->
                    'catelogId': this.dataForm.catelogPath[this.dataForm.catelogPath.length - 1]
                  })
                }).then(({data}) => {
                  if (data && data.code === 0) {
                    this.$message({
                      message: '操作成功',
                      type: 'success',
                      duration: 1500,
                      onClose: () => {
                        this.visible = false
                        this.$emit('refreshDataList')
                      }
                    })
                  } else {
                    this.$message.error(data.msg)
                  }
                })
              }
            })
          }
        },
        <!-- 8.调用分类获取方法 -->
        created () {
          this.getCategorys()
        }
      }
    </script>
    

10.4 前后端联调:修改 级联选择器回显💡

API:添加分类路径字段

  1. AttrGroupEntity:添加分类路径字段

    @Data
    @TableName("pms_attr_group")
    public class AttrGroupEntity implements Serializable {
    	/**
    	 * 所属分类路劲
    	 */
    	@TableField(exist = false)
    	private Long[] catelogPath;
    }
    
  2. AttrGroupController:设置分类路径字段

    /**
     * 信息
     */
    @RequestMapping("/info/{attrGroupId}")
    public R info(@PathVariable("attrGroupId") Long attrGroupId){
    	AttrGroupEntity attrGroup = attrGroupService.getById(attrGroupId);
        //1.获取分类id
        Long catelogId = attrGroup.getCatelogId();
        //2.根据分类id获取分类路径
        attrGroup.setCatelogPath(categoryService.findCatelogPath(catelogId));
    
        return R.ok().put("attrGroup", attrGroup);
    }
    
  3. CategoryService:获取分类路径

    public interface CategoryService extends IService<CategoryEntity> {
        /**
         * 获取分类路径
         * @param catelogId
         * @return
         */
        Long[] findCatelogPath(Long catelogId);
    }
    
  4. CategoryServiceImpl:获取分类路径

    @Service("categoryService")
    public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
        /**
         * 属性分组:获取分类路径
         * @param catelogId
         * @return
         */
        @Override
        public Long[] findCatelogPath(Long catelogId) {
            List<Long> result=new ArrayList<>();
            findParentPath(catelogId, result);
            Collections.reverse(result);
            return result.toArray(new Long[result.size()]);
        }
        //递归获取分类路径
        private void findParentPath(Long catelogId,List<Long> result){
            result.add(catelogId);
            CategoryEntity category = baseMapper.selectById(catelogId);
            if (!category.getParentCid().equals(0l)){
                findParentPath(category.getParentCid(),result);
            }
        }
    }
    

前端

  • components/upload/attrgroup-add-or-update.vue

    <script>
      export default {
        data () {
        methods: {
          init (id) {
            this.dataForm.attrGroupId = id || 0
            this.visible = true
            this.$nextTick(() => {
              this.$refs['dataForm'].resetFields()
              if (this.dataForm.attrGroupId) {
                this.$http({
                  url: this.$http.adornUrl(`/product/attrgroup/info/${this.dataForm.attrGroupId}`),
                  method: 'get',
                  params: this.$http.adornParams()
                }).then(({data}) => {
                  if (data && data.code === 0) {
                    this.dataForm.attrGroupName = data.attrGroup.attrGroupName
                    this.dataForm.sort = data.attrGroup.sort
                    this.dataForm.descript = data.attrGroup.descript
                    this.dataForm.icon = data.attrGroup.icon
                    this.dataForm.catelogId = data.attrGroup.catelogId
                    <!-- 1.初始化弹窗时获取分类路径 -->
                    this.dataForm.catelogPath = data.attrGroup.catelogPath
                  }
                })
              }
            })
          }
      }
    </script>
    

10.5 前端开发:优化

  1. 对话框关闭清空分类路径
  2. 分类级联选择器添加可搜索功能
<template>
  <!-- 1.对话框关闭清空分类路径 -->
  <el-dialog
    :title="!dataForm.attrGroupId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @closed="dialogClose">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="所属分类id" prop="catelogId">
      <!-- 2.添加可搜索功能 -->
      <el-cascader filterable placeholder="试试搜索:手机" v-model="dataForm.catelogPath" :options="categorys"  :props="props"></el-cascader>
    </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
  export default {
    methods: {
      dialogClose () {
        this.dataForm.catelogPath = []
      }
    }
  }
</script>

10.6 API:查询全部 优化模糊查询💡

在这里插入图片描述

  1. AttrGroupController

    public class AttrGroupController {
        @Autowired
        private AttrGroupService attrGroupService;
        /**
         * 列表:三级分类+模糊查询
         */
        @RequestMapping("/list/{catelogId}")
        public R list(@RequestParam Map<String, Object> params,@PathVariable(name = "catelogId") Long catelogId){
            PageUtils page = attrGroupService.queryPage(params,catelogId);
    
            return R.ok().put("page", page);
        }
    }
    
  2. AttrGroupService

    public interface AttrGroupService extends IService<AttrGroupEntity> {
        /**
         * 列表:三级分类+模糊查询
         */
        PageUtils queryPage(Map<String, Object> params, Long catelogId);
    }
    
  3. AttrGroupServiceImpl:先判断是否有模糊查询,再判断查询全部还是查询指定三级分类

    @Service("attrGroupService")
    public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
        /**
         * 列表:三级分类+模糊查询
         * catelogId=0:查询所有
         */
        @Override
        public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
            // 获取模糊查询参数
            String key = (String) params.get("key");
            QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
            // 1.有无模糊查询
            if(!StringUtils.isNullOrEmpty(key)){
                wrapper.and(item->{
                    item.eq("attr_group_id",key).or().like("attr_group_name",key);
                });
            }
            // 2.1 catelogId=0:查询所有
            if(catelogId.equals(0l)){
                IPage<AttrGroupEntity> page = this.page(
                        new Query<AttrGroupEntity>().getPage(params),
                        wrapper
                );
                return new PageUtils(page);
            }else {
                // 2.2 查询指定三级分类
                IPage<AttrGroupEntity> page = this.page(
                        new Query<AttrGroupEntity>().getPage(params),
                        wrapper.eq("catelog_id",catelogId)
                );
                return new PageUtils(page);
            }
        }
    }
    

10.7 API:查询 关联的属性💡

在这里插入图片描述

  1. AttrGroupController:查询分组关联的属性

    @RestController
    @RequestMapping("product/attrgroup")
    public class AttrGroupController {
        @Resource
        private AttrService attrService;
    
        /**
         * 查询分组已经关联的属性
         */
        @RequestMapping("/{attrgroupId}/attr/relation")
        public R attrGroupRelation(@PathVariable(name = "attrgroupId") Long attrgroupId){
            List<AttrEntity> entities=attrService.attrGroupRelation(attrgroupId);
    
            return R.ok().put("data", entities);
        }
    }
    
  2. AttrService:查询分组关联的属性

    public interface AttrService extends IService<AttrEntity> {
        /**
         * 查询分组已经关联的属性
         */
        List<AttrEntity> attrGroupRelation(Long attrgroupId);
    }
    
  3. AttrServiceImpl:查询分组关联的属性

    @Service("attrService")
    public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
        @Resource
        AttrAttrgroupRelationService attrAttrgroupRelationService;
        @Resource
        AttrService attrService;
    
        /**
         * 查询分组已经关联的属性
         */
        @Override
        public List<AttrEntity> attrGroupRelation(Long attrgroupId) {
            //1.在关联表中查出所有属性id
            List<AttrAttrgroupRelationEntity> entityList = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
            List<Long> attrIds = entityList.stream().map(item -> {
                return item.getAttrId();
            }).collect(Collectors.toList());
            //非空判断
            if(attrIds==null || attrIds.size()==0) return null;
            //2.利用属性id查询出所有属性
            Collection<AttrEntity> attrEntities = attrService.listByIds(attrIds);
            return (List<AttrEntity>) attrEntities;
        }
    }
    

10.8 API:删除 关联的属性💡

在这里插入图片描述

  1. 创建用来接收删除关联关系的VO:cn/lzwei/bilimall/product/vo/AttrRelationVo.java

    @Data
    public class AttrRelationVo {
        /**
         * 属性组di
         */
        private Long attrGroupId;
        /**
         * 属性id
         */
        private Long attrId;
    }
    
  2. AttrGroupController

    @RestController
    @RequestMapping("product/attrgroup")
    public class AttrGroupController {
        @Resource
        private AttrAttrgroupRelationService attrAttrgroupRelationService;
    
        /**
         * 批量删除属性与分组的关联
         */
        @PostMapping("/attr/relation/delete")
        public R deleteAttrGroupRelation(@RequestBody AttrRelationVo[] attrRelationVo){
            attrAttrgroupRelationService.deleteBatch(attrRelationVo);
            return R.ok();
        }
    }
    
  3. AttrAttrgroupRelationService

    public interface AttrAttrgroupRelationService extends IService<AttrAttrgroupRelationEntity> {
        /**
         * 批量删除属性与分组的关联
         */
        void deleteBatch(AttrRelationVo[] attrRelationVo);
    }
    
  4. AttrAttrgroupRelationServiceImpl

    @Service("attrAttrgroupRelationService")
    public class AttrAttrgroupRelationServiceImpl extends ServiceImpl<AttrAttrgroupRelationDao, AttrAttrgroupRelationEntity> implements AttrAttrgroupRelationService {
        @Resource
        AttrAttrgroupRelationDao attrAttrgroupRelationDao;
        
        /**
         * 批量删除属性与分组的关联
         */
        @Override
        public void deleteBatch(AttrRelationVo[] attrRelationVo) {
            //1.将VO数组转换为对应的Entry集合
            List<AttrAttrgroupRelationEntity> collect = Arrays.stream(attrRelationVo).map(item -> {
                AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
                entity.setAttrGroupId(item.getAttrGroupId());
                entity.setAttrId(item.getAttrId());
                return entity;
            }).collect(Collectors.toList());
            //2.遍历集合进行删除
            attrAttrgroupRelationDao.deleteAttrGroupRelation(collect);
        }
    }
    

10.9 API:查询 可以新增关联的属性💡

在这里插入图片描述

  1. AttrGroupController:查询分组可以新增关联的属性

    @RestController
    @RequestMapping("product/attrgroup")
    public class AttrGroupController {
        @Resource
        private AttrService attrService;
        
        /**
         * 查询分组可以新增关联的属性
         */
        @RequestMapping("/{attrgroupId}/noattr/relation")
        public R noAttrGroupRelation(@RequestParam Map<String, Object> params,@PathVariable(name = "attrgroupId") Long attrgroupId){
            PageUtils page = attrService.noAttrGroupRelation(params,attrgroupId);
            return R.ok().put("page", page);
        }
    }
    
  2. AttrService:查询分组可以新增关联的属性

    public interface AttrService extends IService<AttrEntity> {
        /**
         * 查询分组可以新增关联的属性
         */
        PageUtils noAttrGroupRelation(Map<String, Object> params, Long attrgroupId);
    }
    
  3. AttrServiceImpl:查询分组可以新增关联的属性

    @Service("attrService")
    public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
        @Resource
        AttrAttrgroupRelationService attrAttrgroupRelationService;
        @Resource
        AttrGroupService attrGroupService;
        @Resource
        AttrService attrService;
        
        /**
         * 查询分组可以新增关联的属性
         */
        @Override
        public PageUtils noAttrGroupRelation(Map<String, Object> params, Long attrgroupId) {
            //1.获得分类id
            AttrGroupEntity attrGroup = attrGroupService.getById(attrgroupId);
            Long catelogId = attrGroup.getCatelogId();
            //3.获得分类下的所有属性组id
            List<AttrGroupEntity> groupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
            List<Long> groupIds = groupEntities.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());
            //4.获得所有已于属性组关联的属性id
            QueryWrapper<AttrAttrgroupRelationEntity> relationWrapper = new QueryWrapper<>();
            if (groupIds!=null && groupIds.size()>0){
                relationWrapper.in("attr_group_id", groupIds);
            }
            List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.list(relationWrapper);
            List<Long> attrIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
            //5.获得当前分类下 剔除这些属性、销售属性 后剩下的属性
            QueryWrapper<AttrEntity> attrWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrType.ATTR_TYPE_BASE.getCode());
            //模糊查询
            String key = (String) params.get("key");
            if(!StringUtils.isNullOrEmpty(key)){
                attrWrapper.and(item->{
                    item.eq("attr_id",key).or().like("attr_name",key);
                });
            }
            if (attrIds!=null && attrIds.size()>0){
                attrWrapper.notIn("attr_id", attrIds);
            }
            IPage<AttrEntity> page=attrService.page(
                    new Query<AttrEntity>().getPage(params),
                    attrWrapper
            );
            return new PageUtils(page);
        }
    }
    

10.10 API:新增 关联的属性💡

在这里插入图片描述

  1. AttrGroupController:属性组批量关联属性

    @RestController
    @RequestMapping("product/attrgroup")
    public class AttrGroupController {
        @Resource
        private AttrAttrgroupRelationService attrAttrgroupRelationService;
    
        /**
         * 属性组批量关联属性
         */
        @PostMapping("/attr/relation")
        public R saveAttrRelation(@RequestBody List<AttrRelationVo> relationVo){
            attrAttrgroupRelationService.addBatch(relationVo);
            return R.ok();
        }
    }
    
  2. AttrAttrgroupRelationService:属性组批量关联属性

    public interface AttrAttrgroupRelationService extends IService<AttrAttrgroupRelationEntity> {
        /**
         * 属性组批量关联属性
         */
        void addBatch(List<AttrRelationVo> relationVo);
    }
    
  3. AttrAttrgroupRelationServiceImpl:属性组批量关联属性

    @Service("attrAttrgroupRelationService")
    public class AttrAttrgroupRelationServiceImpl extends ServiceImpl<AttrAttrgroupRelationDao, AttrAttrgroupRelationEntity> implements AttrAttrgroupRelationService {
        /**
         * 属性组批量关联属性
         */
        @Override
        public void addBatch(List<AttrRelationVo> relationVo) {
            //1.将 VO 转换为 Entity
            List<AttrAttrgroupRelationEntity> entities = relationVo.stream().map(item -> {
                AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
                entity.setAttrId(item.getAttrId());
                entity.setAttrGroupId(item.getAttrGroupId());
                return entity;
            }).collect(Collectors.toList());
            //2.批量保存
            this.saveBatch(entities);
        }
    }
    

十一、商品服务&平台属性&属性⚠️

11.1 API:新增 同步属性属性分组表

在这里插入图片描述

  1. 创建接收参数的Vo:cn/lzwei/bilimall/product/vo/AttrVo.java

    @Data
    public class AttrVo {
        ...
        /**
         * 增加 属性分组id
         */
        private Long attrGroupId;
    }
    
  2. AttrController

    @RestController
    @RequestMapping("product/attr")
    public class AttrController {
        @Autowired
        private AttrService attrService;
        /**
         * 保存:同步属性属性分组表
         */
        @RequestMapping("/save")
        public R save(@RequestBody AttrVo attr){
    		attrService.saveAttr(attr);
    
            return R.ok();
        }
    }
    
  3. AttrService

    public interface AttrService extends IService<AttrEntity> {
        /**
         * 保存:同步属性属性分组表
         */
        void saveAttr(AttrVo attr);
    }
    
  4. AttrServiceImpl:保存&同步属性属性分组表

    @Service("attrService")
    public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
        @Resource
        AttrAttrgroupRelationDao attrAttrgroupRelationDao;
        /**
         * 保存:同步属性属性分组表
         */
        @Transactional
        @Override
        public void saveAttr(AttrVo attr) {
            //1.保存属性表
            AttrEntity attrEntity = new AttrEntity();
            BeanUtils.copyProperties(attr,attrEntity);
            this.save(attrEntity);
            //2.保存属性属性分组表
            Long attrGroupId = attr.getAttrGroupId();
            if (attrGroupId!=null){
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }
    

11.2 API:查询 包括所属分类&分组

在这里插入图片描述

  1. 创建响应数据的Vo:cn/lzwei/bilimall/product/vo/AttrRespVo.java

    @Data
    public class AttrRespVo extends AttrVo {
        /**
         * 分类名
         */
        private String catelogName;
        /**
         * 分组名
         */
        private String groupName;
    }
    
  2. AttrController

    @RestController
    @RequestMapping("product/attr")
    public class AttrController {
        @Autowired
        private AttrService attrService;
        /**
         * 查询:分类、模糊查询(返回包括分类名、分组名)
         */
        @RequestMapping("/base/list/{categoryId}")
        public R baseAttrList(@RequestParam Map<String, Object> params,@PathVariable(value = "categoryId") Long categoryId){
            PageUtils page = attrService.queryBaseAttr(params,categoryId);
    
            return R.ok().put("page", page);
        }
    }
    
  3. AttrService

    public interface AttrService extends IService<AttrEntity> {
        /**
         * 查询:分类、模糊查询(返回包括分类名、分组名)
         */
        PageUtils queryBaseAttr(Map<String, Object> params, Long categoryId);
    }
    
  4. AttrServiceImpl:查询:分类、模糊查询(返回包括分类名、分组名)

    @Service("attrService")
    public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
        @Resource
        AttrAttrgroupRelationDao attrAttrgroupRelationDao;
        @Resource
        CategoryDao categoryDao;
        @Resource
        AttrGroupDao attrGroupDao;
        
        /**
         * 查询:分类、模糊查询(返回包括分类名、分组名)
         */
        @Override
        public PageUtils queryBaseAttr(Map<String, Object> params, Long categoryId) {
            QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
            //1.模糊查询
            String key = (String) params.get("key");
            if(!StringUtils.isNullOrEmpty(key)){
                queryWrapper.and(item->{
                    item.eq("attr_id",key).or().like("attr_name",key);
                });
            }
            //2.分类查询
            if(!categoryId.equals(0l)){
                queryWrapper.eq("catelog_id",categoryId);
            }
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    queryWrapper
            );
    
            PageUtils pageUtils = new PageUtils(page);
            List<AttrEntity> records = page.getRecords();
            List<AttrRespVo> attrRespVoList = records.stream().map(item -> {
                AttrRespVo attrRespVo = new AttrRespVo();
                BeanUtils.copyProperties(item,attrRespVo);
                //3.分类名:查询分类表
                CategoryEntity category = categoryDao.selectById(item.getCatelogId());
                if(category!=null){
                    attrRespVo.setCatelogName(category.getName());
                }
                //4.分组名:需要联表
                AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId()));
                if (attrAttrgroupRelation != null){
                    Long attrGroupId = attrAttrgroupRelation.getAttrGroupId();
                    if(attrGroupId!=null){
                        attrRespVo.setGroupName(attrGroupDao.selectById(attrGroupId).getAttrGroupName());
                    }
                }
                return attrRespVo;
            }).collect(Collectors.toList());
            pageUtils.setList(attrRespVoList);
            return pageUtils;
        }
    }
    

11.3 API:修改 回显&同步属性属性分组表

在这里插入图片描述

  1. 修改响应数据的Vo:cn/lzwei/bilimall/product/vo/AttrRespVo.java:用于分类回显

    @Data
    public class AttrRespVo extends AttrVo {
        /**
         * 分类名
         */
        private String catelogName;
        /**
         * 分组名
         */
        private String groupName;
        /**
         * 分类路径
         */
        private Long[] catelogPath;
    }
    
  2. AttrController:回显—分类路径、修改—同步属性属性分组表

    @RestController
    @RequestMapping("product/attr")
    public class AttrController {
        @Autowired
        private AttrService attrService;
        /**
         * 信息:修改时信息回显
         */
        @RequestMapping("/info/{attrId}")
        public R info(@PathVariable("attrId") Long attrId){
            AttrRespVo attrRespVo=attrService.attrInfo(attrId);
    
            return R.ok().put("attr", attrRespVo);
        }
        /**
         * 修改:同步属性属性分组表
         */
        @RequestMapping("/update")
        public R update(@RequestBody AttrVo attrVo){
    		attrService.updateAttr(attrVo);
    
            return R.ok();
        }
    }
    
  3. AttrService:回显—分类路径、修改—同步属性属性分组表

    public interface AttrService extends IService<AttrEntity> {
        /**
         * 信息:修改时信息回显
         */
        AttrRespVo attrInfo(Long attrId);
    
        /**
         * 修改:同步属性属性分组表
         */
        void updateAttr(AttrVo attrVo);
    }
    
  4. AttrServiceImpl:回显—分类路径、修改—同步属性属性分组表

    @Service("attrService")
    public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
        @Resource
        AttrAttrgroupRelationDao attrAttrgroupRelationDao;
        @Resource
        CategoryDao categoryDao;
        @Resource
        AttrGroupDao attrGroupDao;
        @Resource
        CategoryService categoryService;
        
        /**
         * 信息:修改时信息回显
         */
        @Override
        public AttrRespVo attrInfo(Long attrId) {
            //1.基本信息
            AttrRespVo attrRespVo=new AttrRespVo();
            AttrEntity attr = this.getById(attrId);
            BeanUtils.copyProperties(attr,attrRespVo);
            //2.分组信息
            AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (attrAttrgroupRelation != null){
                attrRespVo.setAttrGroupId(attrAttrgroupRelation.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                if(attrGroupEntity!=null){
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            //3.分类名
            CategoryEntity category = categoryDao.selectById(attr.getCatelogId());
            if(category!=null){
                attrRespVo.setCatelogName(category.getName());
            }
            //4.分类路径
            attrRespVo.setCatelogPath(categoryService.findCatelogPath(attr.getCatelogId()));
    
            return attrRespVo;
        }
    
        /**
         * 修改:同步属性属性分组表
         */
        @Transactional
        @Override
        public void updateAttr(AttrVo attrVo) {
            //1.修改基本信息
            AttrEntity attr = new AttrEntity();
            BeanUtils.copyProperties(attrVo,attr);
            this.updateById(attr);
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelation.setAttrId(attrVo.getAttrId());
            attrAttrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
            if(count>0){
                //2.修改
                attrAttrgroupRelationDao.update(attrAttrgroupRelation,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrVo.getAttrId()));
            }else{
                //3.新增
                attrAttrgroupRelationDao.insert(attrAttrgroupRelation);
            }
        }
    }
    

11.4 优化:区分销售属性⚠️

在这里插入图片描述

  1. 公共服务 中创建属性类型枚举:cn/lzwei/common/constant/ProductConstant.java

    public class ProductConstant {
        public enum AttrType{
            ATTR_TYPE_BASE(1,"基本属性"),ATTR_TYPE_SALE(0,"销售属性");
            private Integer code;
            private String msg;
            AttrType(Integer code,String msg){
                this.code=code;
                this.msg=msg;
            }
    
            public Integer getCode() {
                return code;
            }
    
            public String getMsg() {
                return msg;
            }
        }
    }
    
  2. AttrController

    @RestController
    @RequestMapping("product/attr")
    public class AttrController {
        @Autowired
        private AttrService attrService;
    
        /**
         * 查询:分类、模糊查询(返回包括分类名、分组名)。区分销售属性、规格参数
         */
        @RequestMapping("/{type}/list/{categoryId}")
        public R baseAttrList(@RequestParam Map<String, Object> params,
                              @PathVariable(value = "categoryId") Long categoryId,
                              @PathVariable(value = "type") String type){
            PageUtils page = attrService.queryBaseAttr(params,categoryId,type);
    
            return R.ok().put("page", page);
        }
        /**
         * 保存:区分销售属性再同步属性属性分组表
         */
        @RequestMapping("/save")
        public R save(@RequestBody AttrVo attr){
    		attrService.saveAttr(attr);
    
            return R.ok();
        }
        /**
         * 信息:修改时信息回显。区分销售属性、规格参数
         */
        @RequestMapping("/info/{attrId}")
        public R info(@PathVariable("attrId") Long attrId){
            AttrRespVo attrRespVo=attrService.attrInfo(attrId);
    
            return R.ok().put("attr", attrRespVo);
        }
        /**
         * 修改:规格参数才需同步属性属性分组表。
         */
        @RequestMapping("/update")
        public R update(@RequestBody AttrVo attrVo){
    		attrService.updateAttr(attrVo);
    
            return R.ok();
        }
    }
    
  3. AttrService

    public interface AttrService extends IService<AttrEntity> {
    
        PageUtils queryPage(Map<String, Object> params);
    
        /**
         * 信息:修改时信息回显。区分销售属性、规格参数
         */
        AttrRespVo attrInfo(Long attrId);
        /**
         * 保存:区分销售属性再同步属性属性分组表
         */
        void saveAttr(AttrVo attr);
         /**
         * 查询:分类、模糊查询(返回包括分类名、分组名)
         */
        PageUtils queryBaseAttr(Map<String, Object> params, Long categoryId, String type);
        /**
         * 修改:规格参数才需同步属性属性分组表。
         */
        void updateAttr(AttrVo attrVo);
    }
    
  4. AttrServiceImpl

    @Service("attrService")
    public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
        @Resource
        AttrAttrgroupRelationDao attrAttrgroupRelationDao;
        @Resource
        CategoryDao categoryDao;
        @Resource
        AttrGroupDao attrGroupDao;
        @Resource
        CategoryService categoryService;
    
        /**
         * 查询:分类、模糊查询(返回包括分类名、分组名)
         */
        @Override
        public PageUtils queryBaseAttr(Map<String, Object> params, Long categoryId, String type) {
            QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_type","base".equalsIgnoreCase(type)?1:0);
            //1.模糊查询
            String key = (String) params.get("key");
            if(!StringUtils.isNullOrEmpty(key)){
                queryWrapper.and(item->{
                    item.eq("attr_id",key).or().like("attr_name",key);
                });
            }
            //2.分类查询
            if(!categoryId.equals(0l)){
                queryWrapper.eq("catelog_id",categoryId);
            }
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    queryWrapper
            );
    
            PageUtils pageUtils = new PageUtils(page);
            List<AttrEntity> records = page.getRecords();
            List<AttrRespVo> attrRespVoList = records.stream().map(item -> {
                AttrRespVo attrRespVo = new AttrRespVo();
                BeanUtils.copyProperties(item,attrRespVo);
                //3.分类名:查询分类表
                CategoryEntity category = categoryDao.selectById(item.getCatelogId());
                if(category!=null){
                    attrRespVo.setCatelogName(category.getName());
                }
                Integer attrType = item.getAttrType();
                //只有规格参数才有属性分组
                if(attrType== ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()){
                    //4.分组名:需要联表
                    AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId()));
                    if (attrAttrgroupRelation != null){
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                        if(attrGroupEntity!=null){
                            attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                        }
                    }
                }
                return attrRespVo;
            }).collect(Collectors.toList());
            pageUtils.setList(attrRespVoList);
            return pageUtils;
        }
        /**
         * 保存:区分销售属性再同步属性属性分组表
         */
        @Transactional
        @Override
        public void saveAttr(AttrVo attr) {
            //1.保存属性表
            AttrEntity attrEntity = new AttrEntity();
            BeanUtils.copyProperties(attr,attrEntity);
            this.save(attrEntity);
            Integer attrType = attr.getAttrType();
            //只有规格参数才有属性分组
            if(attrType== ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()){
                //2.保存属性属性分组表
                Long attrGroupId = attr.getAttrGroupId();
                if (attrGroupId!=null){
                    AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                    attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                    attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
                    attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
                }
            }
        }
        /**
         * 信息:修改时信息回显。区分销售属性、规格参数
         */
        @Override
        public AttrRespVo attrInfo(Long attrId) {
            //1.基本信息
            AttrRespVo attrRespVo=new AttrRespVo();
            AttrEntity attr = this.getById(attrId);
            BeanUtils.copyProperties(attr,attrRespVo);
            Integer attrType = attr.getAttrType();
            //只有规格参数才有属性分组
            if(attrType== ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()){
                //2.分组信息
                AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
                if (attrAttrgroupRelation != null){
                    attrRespVo.setAttrGroupId(attrAttrgroupRelation.getAttrGroupId());
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                    if(attrGroupEntity!=null){
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            //3.分类名
            CategoryEntity category = categoryDao.selectById(attr.getCatelogId());
            if(category!=null){
                attrRespVo.setCatelogName(category.getName());
            }
            //4.分类路径
            attrRespVo.setCatelogPath(categoryService.findCatelogPath(attr.getCatelogId()));
    
            return attrRespVo;
        }
        /**
         * 修改:规格参数才需同步属性属性分组表。
         */
        @Override
        public void updateAttr(AttrVo attrVo) {
            //1.修改基本信息
            AttrEntity attr = new AttrEntity();
            BeanUtils.copyProperties(attrVo,attr);
            this.updateById(attr);
            Integer attrType = attr.getAttrType();
            //只有规格参数才有属性分组
            if(attrType== ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()){
                Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
                AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelation.setAttrId(attrVo.getAttrId());
                attrAttrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
                if(count>0){
                    //2.修改
                    attrAttrgroupRelationDao.update(attrAttrgroupRelation,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrVo.getAttrId()));
                }else{
                    //3.新增
                    attrAttrgroupRelationDao.insert(attrAttrgroupRelation);
                }
            }
        }
    }
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愿你满腹经纶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值