✅P75_品牌管理-品牌分类关联与级联更新
品牌分页问题
出现问题:分页的总条数统计不正确
解决方案:mybatis-plus中要使用分页,需要配置分页插件,以下为旧版配置,新版配置参考:分页插件
cfmall-product/src/main/java/com/gyz/cfmall/product/config/MyBatisConfig.java
package com.gyz.cfmall.product.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @Description
* @Author GongYuZhuo
* @Version 1.0.0
*/
@Configuration
@EnableTransactionManagement //开启使用
@MapperScan("com.gyz.cfmall.product.dao")
public class MyBatisConfig {
//引入分页插件(旧版)
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
paginationInterceptor.setOverflow(true);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
paginationInterceptor.setLimit(1000);
return paginationInterceptor;
}
}
再次查看页面条数显示正确
模糊查询
页面支持根据id和name进行模糊查询
实现效果:
代码编写:
cfmall-product/src/main/java/com/gyz/cfmall/product/controller/BrandController.java
@Autowired
private BrandService brandService;
/**
* 列表
*/
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params) {
PageUtils page = brandService.queryPage(params);
return R.ok().put("page", page);
}
cfmall-product/src/main/java/com/gyz/cfmall/product/service/impl/BrandServiceImpl.java
@Override
public PageUtils queryPage(Map<String, Object> params) {
//SELECT brand_id,name,logo,show_status,sort,descript,first_letter FROM pms_brand WHERE (brand_id = ? OR name LIKE ?) LIMIT ?,?
//获取key
String key = (String) params.get("key");
QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
//如果传过来的数据不是空的,就进行多参数查询
if (!StringUtils.isEmpty(key)) {
queryWrapper.eq("brand_id", key).or().like("name", key);
}
IPage<BrandEntity> page = this.page(
new Query<BrandEntity>().getPage(params),
queryWrapper
);
return new PageUtils(page);
}
品牌关联分类
一个品牌可以有多个分类,一个分类下有多个品牌,是多对多的关系。品牌分类关联表:pms_category_brand_relation
实现效果
点击“关联分类”,在弹窗中选择“新增关联”,然后选择分类,添加成功!移除操作没有演示
前端实现
src\views\modules\product\brand.vue
触发关联分类函数
页面添加关联分类
按钮,
<el-table-column fixed="right" header-align="center" align="center" width="200" label="操作">
<template slot-scope="scope">
<el-button type="text" size="small" @click="updateCatelogHandle(scope.row.brandId)">关联分类</el-button>
</template>
</el-table-column>
点击关联分类
按钮,触发updateCatelogHandle(scope.row.brandId)
方法,调用后台 获取品牌分类关联列表 接口,弹窗显示品牌分类关联列表
method{
//点击关联分类触发的函数,拉取列表
updateCatelogHandle(brandId) {
//触发弹窗
this.dialogTableVisible = true;
this.brandId = brandId;
this.getCateRelation();
},
//展示品牌分类关联列表
getCateRelation() {
this.$http({
url: this.$http.adornUrl("/product/categorybrandrelation/catelog/list"),
method: "get",
params: this.$http.adornParams({
brandId: this.brandId
})
}).then(({ data }) => {
this.categoryBrandRelation = data.data;
});
},
}
对话框内容详解:
@closed="dialogClosed"
:使用dialog的事件,当关闭对话框时将categoryPath置为空,即在新增完品牌分类关联后,再次选择三级分类时,选择框应为空;- 级联选择器:选择分类使用,
<el-popover>
: 给表格里增加弹窗; @click="addCatelogSelect"
:点击新增关联
选择分类后,点击确定
按钮触发的方法,调用后台 保存品牌分类关联 接口实现落库;:data="categoryBrandRelation"
:保存品牌分类关联列表数据;deleteRow(scope.row.id, scope.row.brandId)
:在关联分类
列表中移除数据触发的方法,调用后台 移除品牌分类关联 接口;
<template>
<div class="mod-config">
<!-- 点击关联分类弹出的对话框 -->
<el-dialog title="关联分类" :visible.sync="dialogTableVisible" width="30%" @closed="dialogClosed">
<!-- <el-popover> : 给表格里增加弹窗, popCatelogSelectVisible:false,默认为false时,只有点击才打开弹窗-->
<el-popover placement="right-end" v-model="popCatelogSelectVisible">
<!-- 级联选择器-->
<el-cascader v-model="catelogPath" :options="categories" :props="props">
</el-cascader>
<div style="text-align: right; margin: 0">
<el-button size="mini" type="text" @click="popCatelogSelectVisible = false">取消</el-button>
<el-button type="primary" size="mini" @click="addCatelogSelect">确定</el-button>
</div>
<el-button slot="reference">新增关联</el-button>
</el-popover>
<el-table :data="categoryBrandRelation" style="width: 100%;">
<!-- 此id为数据表中的唯一id -->
<el-table-column prop="id" label="id"></el-table-column>
<el-table-column property="brandName" label="品牌名称"></el-table-column>
<el-table-column property="catelogName" label="分类名称"></el-table-column>
<el-table-column fixed="right" label="操作" width="120">
<template slot-scope="scope">
<!-- 在删除品牌分类关联时,由于品牌和分类是多对多的关系,只有根据表中唯一id删除,才能保证数据不被多删 -->
<el-button @click.native.prevent="deleteRow(scope.row.id, scope.row.brandId)" type="text" size="small">
移除
</el-button>
</template>
</el-table-column>
</el-table>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogTableVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogTableVisible = false">确 定</el-button>
</div>
</el-dialog>
</div>
</template>
方法定义
methods: {
//置空分类选择框
dialogClosed() {
this.catelogPath = [];
},
//点击关联分类触发的函数,拉取列表
updateCatelogHandle(brandId) {
//触发弹窗
this.dialogTableVisible = true;
this.brandId = brandId;
this.getCateRelation();
},
//新增品牌关联分类
addCatelogSelect() {
this.popCatelogSelectVisible = false;
this.$http({
url: this.$http.adornUrl("/product/categorybrandrelation/save"),
method: "post",
data: this.$http.adornData({ brandId: this.brandId, catelogId: this.catelogPath[this.catelogPath.length - 1] }, false)
}).then(({ data }) => {
this.$message({
message: "新增成功",
type: "success"
});
this.getCateRelation();
});
},
//展示品牌分类关联表
getCateRelation() {
this.$http({
url: this.$http.adornUrl("/product/categorybrandrelation/catelog/list"),
method: "get",
params: this.$http.adornParams({
brandId: this.brandId
})
}).then(({ data }) => {
this.categoryBrandRelation = data.data;
});
},
//移除关联分类
deleteRow(id, brandId) {
console.log("移除关联分类传参为:", id);
this.$http({
url: this.$http.adornUrl("/product/categorybrandrelation/delete"),
method: 'post',
data: this.$http.adornData([id], false)
}).then((data) => {
this.$message({
message: "移除成功",
type: "success"
});
//移除品牌分类关联后重新获取列表
this.getCateRelation();
})
}
}
}
完整前端代码
src\views\modules\product\brand.vue
<template>
<div class="mod-config">
<el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
<el-form-item>
<el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
</el-form-item>
<el-form-item>
<el-button @click="getDataList()">查询</el-button>
<el-button v-if="isAuth('product:brand:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
<el-button v-if="isAuth('product:brand:delete')" type="danger" @click="deleteHandle()"
:disabled="dataListSelections.length <= 0">批量删除</el-button>
</el-form-item>
</el-form>
<el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
style="width: 100%;">
<el-table-column type="selection" header-align="center" align="center" width="50">
</el-table-column>
<el-table-column prop="brandId" header-align="center" align="center" label="品牌id">
</el-table-column>
<el-table-column prop="name" header-align="center" align="center" label="品牌名">
</el-table-column>
<el-table-column prop="logo" header-align="center" align="center" label="品牌logo">
<template slot-scope="scope">
<el-image style="width: 100px; height: 60px" :src="scope.row.logo" fit="contain"></el-image>
</template>
</el-table-column>
<el-table-column prop="descript" header-align="center" align="center" label="介绍">
</el-table-column>
<el-table-column prop="showStatus" header-align="center" align="center" label="显示状态">
<template slot-scope="scope">
<el-switch v-model="scope.row.showStatus" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
:inactive-value="0" @change="updateBrandStatus(scope.row)"></el-switch>
</template>
</el-table-column>
<el-table-column prop="firstLetter" header-align="center" align="center" label="检索首字母">
</el-table-column>
<el-table-column prop="sort" header-align="center" align="center" label="排序" width="100">
</el-table-column>
<el-table-column fixed="right" header-align="center" align="center" width="200" label="操作">
<template slot-scope="scope">
<el-button type="text" size="small" @click="updateCatelogHandle(scope.row.brandId)">关联分类</el-button>
<el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.brandId)">修改</el-button>
<el-button type="text" size="small" @click="deleteHandle(scope.row.brandId)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
:page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
layout="total, sizes, prev, pager, next, jumper">
</el-pagination>
<!-- 弹窗, 新增 / 修改 -->
<add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
<!-- 点击关联分类弹出的对话框 -->
<el-dialog title="关联分类" :visible.sync="dialogTableVisible" width="30%" @closed="dialogClosed">
<!-- <el-popover> : 给表格里增加弹窗, popCatelogSelectVisible:false,默认为false时,只有点击才打开弹窗-->
<el-popover placement="right-end" v-model="popCatelogSelectVisible">
<el-cascader v-model="catelogPath" :options="categories" :props="props">
</el-cascader>
<div style="text-align: right; margin: 0">
<el-button size="mini" type="text" @click="popCatelogSelectVisible = false">取消</el-button>
<el-button type="primary" size="mini" @click="addCatelogSelect">确定</el-button>
</div>
<el-button slot="reference">新增关联</el-button>
</el-popover>
<el-table :data="categoryBrandRelation" style="width: 100%;">
<!-- 此id为数据表中的唯一id -->
<el-table-column prop="id" label="id"></el-table-column>
<el-table-column property="brandName" label="品牌名称"></el-table-column>
<el-table-column property="catelogName" label="分类名称"></el-table-column>
<el-table-column fixed="right" label="操作" width="120">
<template slot-scope="scope">
<!-- 在删除品牌分类关联时,由于品牌和分类是多对多的关系,只有根据表中唯一id删除,才能保证数据不被多删 -->
<el-button @click.native.prevent="deleteRow(scope.row.id, scope.row.brandId)" type="text" size="small">
移除
</el-button>
</template>
</el-table-column>
</el-table>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogTableVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogTableVisible = false">确 定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import AddOrUpdate from './brand-add-or-update'
export default {
data() {
return {
brandId: 0,
categoryBrandRelation: [], //品牌分类关联数据
dialogTableVisible: false,
categories: [], //:options="categories",options属性指定选项数组即可渲染出一个级联选择器
props: {
value: "catId", //指定选项的值为选项对象的某个属性值
label: "name", //指定选项标签为选项对象的某个属性值(页面分类数据category对象的name字段)
children: "children" //指定选项的子选项为选项对象的某个属性值(页面分类数据category对象的children)
},
catelogPath: [],
options: "",
popCatelogSelectVisible: false, //表格内弹窗是否打开
dataForm: {
key: ''
},
dataList: [],
pageIndex: 1,
pageSize: 10,
totalPage: 0,
dataListLoading: false,
dataListSelections: [],
addOrUpdateVisible: false
}
},
components: {
AddOrUpdate
},
activated() {
this.getDataList()
},
methods: {
dialogClosed() {
this.catelogPath = [];
},
// 获取数据列表
getDataList() {
this.dataListLoading = false
this.$http({
url: this.$http.adornUrl('/product/brand/list'),
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
})
},
// 每页数
sizeChangeHandle(val) {
this.pageSize = val
this.pageIndex = 1
this.getDataList()
},
// 当前页
currentChangeHandle(val) {
this.pageIndex = val
this.getDataList()
},
// 多选
selectionChangeHandle(val) {
this.dataListSelections = val
},
// 新增 / 修改
addOrUpdateHandle(id) {
this.addOrUpdateVisible = true
this.$nextTick(() => {
this.$refs.addOrUpdate.init(id)
})
},
// 删除
deleteHandle(id) {
var ids = id ? [id] : this.dataListSelections.map(item => {
return item.brandId
})
this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$http({
url: this.$http.adornUrl('/product/brand/delete'),
method: 'post',
data: this.$http.adornData(ids, false)
}).then(({ data }) => {
if (data && data.code === 0) {
this.$message({
message: '操作成功',
type: 'success',
duration: 1500,
onClose: () => {
this.getDataList()
}
})
} else {
this.$message.error(data.msg)
}
})
})
},
//点击关联分类触发的函数,拉取列表
updateCatelogHandle(brandId) {
//触发弹窗
this.dialogTableVisible = true;
this.brandId = brandId;
this.getCateRelation();
},
//初始化三级分类数据
queryCategoryTree() {
this.$http({
url: this.$http.adornUrl('/product/category/list/tree'),
method: 'get'
}).then(({ data }) => {
this.categories = data.data;
});
},
//新增品牌关联分类
addCatelogSelect() {
this.popCatelogSelectVisible = false;
this.$http({
url: this.$http.adornUrl("/product/categorybrandrelation/save"),
method: "post",
data: this.$http.adornData({ brandId: this.brandId, catelogId: this.catelogPath[this.catelogPath.length - 1] }, false)
}).then(({ data }) => {
this.$message({
message: "新增成功",
type: "success"
});
this.getCateRelation();
});
},
//展示品牌分类关联表
getCateRelation() {
this.$http({
url: this.$http.adornUrl("/product/categorybrandrelation/catelog/list"),
method: "get",
params: this.$http.adornParams({
brandId: this.brandId
})
}).then(({ data }) => {
this.categoryBrandRelation = data.data;
});
},
//移除关联分类
deleteRow(id, brandId) {
console.log("移除关联分类传参为:", id);
this.$http({
url: this.$http.adornUrl("/product/categorybrandrelation/delete"),
method: 'post',
data: this.$http.adornData([id], false)
}).then((data) => {
this.$message({
message: "移除成功",
type: "success"
});
//移除品牌分类关联后重新获取列表
this.getCateRelation();
})
}
},
//声明周期创建就初始化三级分类数据
created() {
this.queryCategoryTree();
},
}
</script>
后台实现
获取品牌分类关联列表
cfmall-product/src/main/java/com/gyz/cfmall/product/controller/CategoryBrandRelationController.java
@Autowired
private CategoryBrandRelationService categoryBrandRelationService;
/**
* 获取当前品牌关联的所有分类列表列表
*/
@GetMapping(value = "/catelog/list")
//@RequiresPermissions("product:categorybrandrelation:list")
public R catelogList(@RequestParam Map<String, Object> params, @RequestParam("brandId") Long brandId) {
List<CategoryBrandRelationEntity> data = categoryBrandRelationService.
list(new QueryWrapper<CategoryBrandRelationEntity>().eq("brand_id", brandId));
return R.ok().put("data", data);
}
保存品牌分类关联
cfmall-product/src/main/java/com/gyz/cfmall/product/controller/CategoryBrandRelationController.java
@Autowired
private CategoryBrandRelationService categoryBrandRelationService;
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestBody CategoryBrandRelationEntity categoryBrandRelation) {
categoryBrandRelationService.saveDetail(categoryBrandRelation);
return R.ok();
}
cfmall-product/src/main/java/com/gyz/cfmall/product/service/impl/CategoryBrandRelationServiceImpl.java
@Resource
private BrandDao brandDao;
@Resource
private CategoryDao categoryDao;
@Override
public void saveDetail(CategoryBrandRelationEntity categoryBrandRelation) {
Long brandId = categoryBrandRelation.getBrandId();
Long catelogId = categoryBrandRelation.getCatelogId();
//1、查询品牌详细信息
BrandEntity brandEntity = brandDao.selectById(brandId);
//2、查询分类详细信息
CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
//将信息保存到categoryBrandRelation中
categoryBrandRelation.setBrandName(brandEntity.getName());
categoryBrandRelation.setCatelogName(categoryEntity.getName());
// 保存到数据库中
this.baseMapper.insert(categoryBrandRelation);
}
移除品牌分类关联
cfmall-product/src/main/java/com/gyz/cfmall/product/controller/CategoryBrandRelationController.java
@Autowired
private CategoryBrandRelationService categoryBrandRelationService;
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("product:categorybrandrelation:delete")
public R delete(@RequestBody Long[] ids) {
categoryBrandRelationService.removeByIds(Arrays.asList(ids));
return R.ok();
}
品牌和分类修改同步中间表
修改品牌名时,同步修改关联表pms_category_brand_relation
的品牌名;修改分类名时,同步修改关联表pms_category_brand_relation
的分类名;
品牌修改
cfmall-product/src/main/java/com/gyz/cfmall/product/controller/BrandController.java
@Autowired
private BrandService brandService;
/**
* 修改
*/
@RequestMapping("/update")
public R update(@Validated({UpdateGroup.class}) @RequestBody BrandEntity brand) {
brandService.updateDetail(brand);
return R.ok();
}
cfmall-product/src/main/java/com/gyz/cfmall/product/service/impl/BrandServiceImpl.java
@Resource
private CategoryBrandRelationService categoryBrandRelationService;
@Override
public void updateDetail(BrandEntity brand) {
//保证冗余字段的数据一致
baseMapper.updateById(brand);
if (!StringUtils.isEmpty(brand.getName())) {
//同步更新其他关联表中的数据
categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
//TODO 更新其他关联
}
}
cfmall-product/src/main/java/com/gyz/cfmall/product/service/CategoryBrandRelationService.java
void updateBrand(Long brandId, String name);
cfmall-product/src/main/java/com/gyz/cfmall/product/service/impl/CategoryBrandRelationServiceImpl.java
@Override
public void updateBrand(Long brandId, String name) {
CategoryBrandRelationEntity relationEntity = new CategoryBrandRelationEntity();
relationEntity.setBrandId(brandId);
relationEntity.setBrandName(name);
this.update(relationEntity, new UpdateWrapper<CategoryBrandRelationEntity>().eq("brand_id", brandId));
}
分类修改
cfmall-product/src/main/java/com/gyz/cfmall/product/controller/CategoryController.java
@Autowired
private CategoryService categoryService;
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody CategoryEntity category) {
categoryService.updateCascade(category);
return R.ok();
}
cfmall-product/src/main/java/com/gyz/cfmall/product/service/impl/CategoryServiceImpl.java
@Autowired
private CategoryBrandRelationService categoryBrandRelationService;
@Override
public void updateCascade(CategoryEntity category) {
this.updateById(category);
categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
}
cfmall-product/src/main/java/com/gyz/cfmall/product/service/CategoryBrandRelationService.java
void updateCategory(Long catId, String name);
cfmall-product/src/main/java/com/gyz/cfmall/product/service/impl/CategoryBrandRelationServiceImpl.java
@Override
public void updateCategory(Long catId, String name) {
this.baseMapper.updateCategory(catId, name);
}
cfmall-product/src/main/java/com/gyz/cfmall/product/dao/CategoryBrandRelationDao.java
@Mapper
public interface CategoryBrandRelationDao extends BaseMapper<CategoryBrandRelationEntity> {
void updateCategory(@Param("catId") Long catId, @Param("name") String name);
}
cfmall-product/src/main/resources/mapper/product/CategoryBrandRelationDao.xml
<update id="updateCategory">
update `pms_category_brand_relation` set catelog_name = #{name} where catelog_id = #{catId}
</update>
测试
品牌修改,品牌分类关联列表中也同步修改
分类修改,品牌分类关联列表中也同步修改