123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- 'use strict';
- const Service = require('egg').Service;
- /**
- * 文章操作服务
- */
- class ArticlesService extends Service {
- /**
- * [getArticlesCategoryAllChild 查询分类下所有子分类]
- * @author szjcomo
- * @date 2021-01-27
- * @param {[type]} category_id [description]
- * @return {[type]} [description]
- */
- async getArticlesCategoryAllChild(category_id = 0) {
- let that = this;
- let categorys = await that.getArticlesCategoryAll({attributes:['category_id','category_name','pid'],raw:true});
- let tmp = that.app.szjcomo.arrayRecursion(categorys,category_id,'pid','category_id');
- let data = that.app.szjcomo.arrayRecursiveBack(tmp);
- let arr = [category_id];
- data.forEach(item => {
- arr.push(item.category_id);
- })
- return arr;
- }
- /**
- * [getArticlesCategoryAll 查询所有分类]
- * @author szjcomo
- * @date 2021-01-27
- * @return {[type]} [description]
- */
- async getArticlesCategoryAll(options = {}) {
- let that = this;
- let seq = that.app.Sequelize;
- let default_options = {
- include:[{model:that.app.model.AdminUser,as:'admin_user',attributes:[]}],
- attributes:{
- include:[[seq.col('admin_user.username'),'username']],
- exclude:['admin_id']
- }
- };
- let finalOptions = Object.assign(default_options,options)
- let result = await that.app.model.ArticlesCategory.findAll(finalOptions);
- return result;
- }
- /**
- * [getArticlesCategoryAllParents 查询分类的所有父级分类]
- * @author szjcomo
- * @date 2021-01-27
- * @param {[type]} category_id [description]
- * @return {[type]} [description]
- */
- async getArticlesCategoryAllParents(category_id = 0) {
- let that = this;
- if(category_id == 0) return [];
- let categorys = await that.getArticlesCategoryAll({attributes:['category_id','category_name','pid'],raw:true});
- //将一维数组转换成递归的多维数组
- let tmp = that.app.szjcomo.arrayRecursion(categorys,0,'pid','category_id');
- //将多维数组转换成一维数组并按照层级进行有序排列
- let data = that.app.szjcomo.arrayRecursiveBack(tmp);
- //当前分类总父级有多少个
- let currCategoryTotalParents = 0;
- //当前分类在数组中的下标
- let currCategoryIndex = -1;
- for(let i = 0;i < data.length;i++) {
- let item = data[i];
- if(item.pid == 0) {
- currCategoryTotalParents = 0;
- } else {
- currCategoryTotalParents += 1;
- }
- if(item.category_id == category_id) {
- currCategoryIndex = i;
- break;
- }
- }
- if(currCategoryIndex == -1) return [];
- if(currCategoryTotalParents == 0) {
- let item = data[currCategoryIndex];
- delete item.child;
- return [item];
- }
- let result = [];
- for(let i = currCategoryTotalParents;i >= 0;i--,currCategoryIndex--) {
- let item = data[currCategoryIndex];
- delete item.child;
- result.unshift(item);
- }
- return result;
- }
- }
- module.exports = ArticlesService;
|