关于瑞吉外卖类别(category)
关于他的更改和新增不用说了,和他的员工其实都差不多,也不过多阐述,也没什么值的注意的
就是更改的时候他的回显其实前端已经绑定好了的,说一下删除
删除
当写这个的时候就需要知道的是,当这个分类关联了菜品或者套餐的时候是不能删除的
1.1执行流程
1.页面发送ajax请求,将参数id交到服务端
//删除
deleteHandle(id) {
this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
'confirmButtonText': '确定',
'cancelButtonText': '取消',
'type': 'warning'
}).then(() => {
deleCategory(id).then(res => {
if (res.code === 1) {
this.$message.success('删除成功!')
this.handleQuery()
} else {
this.$message.error(res.msg || '操作失败')
}
}).catch(err => {
this.$message.error('请求出错了:' + err)
})
})
},
2.服务端contoller接收页面数据,调用service进行删除
3.service调用mapper操作数据库
1.2代码
/**
* 编辑
* @param id
* @return
*/
@DeleteMapping
public R<String> delete(Long id){
log.info("删除的id是{}",id);
categoryService.removeById(id);
return R.success("分类删除成功");
}
1.3前面就已经说过了,注意
这里需要查看是否有关联,所以我们需要重写一下removeById的这个方法,加入条件
servicec层
public interface CategoryService extends IService<Category> {
public void remove(Long id);
}
serviceImpl
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService{
@Autowired
private DishService dishService;
@Autowired
private SetmealService setmealService;
@Override
public void remove(Long id) {
//查询当前的分类关联了菜品
LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
int count = dishService.count(dishLambdaQueryWrapper);
if(count>0){
//抛出异常
throw new CustomException("当前分类关联了菜品,不能删除");
}
//查询当前的分类关联了套餐
LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
int count1 = setmealService.count(setmealLambdaQueryWrapper);
if (count1>0){
//抛出异常
throw new CustomException("当前分类关联了套餐,不能删除");
}
//没有的话放行
super.removeById(id);
}
}
关于自定义的这个代码很简单只需要继承一下运行时异常就可以了
public class CustomException extends RuntimeException{
public CustomException(String message){
super(message);
}
}
然后直接丢给全局异常处理器
@ExceptionHandler(CustomException.class)
public R<String> exceptionHandler(CustomException ex){
log.info("错误信息是{}",ex.getMessage());
return R.error(ex.getMessage());
}
lic R<String> exceptionHandler(CustomException ex){
log.info("错误信息是{}",ex.getMessage());
return R.error(ex.getMessage());
}