1. 程式人生 > 實用技巧 >麵包屑的查詢

麵包屑的查詢

看你前臺需要什麼樣子的資料一般來說是一個包含兄弟節點的資料

/**
 * 做麵包屑的查詢,因為前端需要的資料為
 * [{
 *    ownerProductType;{課程型別}
 *    otherProductTypes:[{課程}]
 * }]
 * 所以我們需要封裝一個欄位
 */
public class CourseTypeCrumbsDto {
    //該節點
    private CourseType ownerProductType;
    //兄弟節點
    private List<CourseType> otherProductTypes = new
ArrayList<CourseType>(); }
View Code

然後我們前端發一個請求過來

 @RequestMapping(value="/crumbs/{id}",method= RequestMethod.GET)
    public AjaxResult crumbs(@PathVariable("id")Long id){
        try {
            List<CourseTypeCrumbsDto> crumbsDtos = courseTypeService.crumbs(id);
            return
AjaxResult.me().setResultObj(crumbsDtos); } catch (Exception e) { e.printStackTrace(); return AjaxResult.me().setMessage("儲存物件失敗!"+e.getMessage()); } }
View Code

然後就是我們的service其實很簡單這裡我們把所以父節點及自己的節點存入PATH這個位置這樣我們就可以拿到自己的父節點了

通過父節點查詢他們的兄弟節點就可以實現麵包屑

@Override
    
public List<CourseTypeCrumbsDto> crumbs(Long id) { //1.通過id找到Path中的目錄 CourseType courseType = baseMapper.selectById(id); String path = courseType.getPath(); String[] paths = path.split("\\."); //查詢所有的paths的節點 List<CourseType> courseTypes = baseMapper.selectBatchIds(Arrays.asList(paths)); //儲存麵包屑的值 List<CourseTypeCrumbsDto> crumbsDtos = new ArrayList<CourseTypeCrumbsDto>(); courseTypes.forEach(curentCourseType->{ CourseTypeCrumbsDto courseTypeCrumbsDto = new CourseTypeCrumbsDto(); courseTypeCrumbsDto.setOwnerProductType(curentCourseType); //找到和自己一樣父ID的節點寫個方法需要自己寫 List<CourseType> brothers = baseMapper.selectBrotherByPid(curentCourseType.getPid()); courseTypeCrumbsDto.setOtherProductTypes(brothers); crumbsDtos.add(courseTypeCrumbsDto); }); return crumbsDtos; }
View Code