使用sequelize进行列表排序

官方文档: https://sequelize.org/master/manual/eager-loading.html#ordering-eager-loaded-associations

需求: 上传安卓包的时候,可以拿到一个上传的列表,这时候我要根据上传的时间进行排序,并且拿到最新的版本号,所以这里分2个service进行处理,这里要用sequelize里面提供的order的方法进行排序,不能用sort,因为这里是对所有的数据进行排序.害,只能怪我脑子里面都是前端代码~~~

主要是order: [[ 'versionName', 'DESC' ]],的使用,不难,只是说刚到遇到这里实例记录一下而已

controller

  /**
   * 版本新增列表
   */
  async versionManage() {
    const { ctx } = this
    const { limit, offset } = this.paginationDeal(ctx.request.query)
    const { list, total } = await this.service.versionManage.versionManage.versionManage({ limit, offset })
    let installTotal = 0
    // 计算出安装的总数
    list.forEach(item => {
      installTotal += +item.installEquipmentNum
    })
    this.success({ data: { list, total, installTotal } })
  }

  /**
   * 获取最新的版本以及pkg
   */
  async newestVersion() {
    const data = await this.service.versionManage.versionManage.newestVersion()
    const newestVersion = {
      newVersionName: data[0] && data[0].versionName || '',
      newPkg: data[0] && data[0].pkg || '',
    }
    this.success({ data: newestVersion })
  }

service

'use strict'

const Service = require('egg').Service
// 版本管理
class versionManageService extends Service {
  /**
   * 版本更新信息列表
   * @param { Object } object 传入的对象
   * @param { String } object.limit 限制的返回的数据行数
   * @param { String } object.offset 返回行之前忽略多少行
   */
  async versionManage({ limit, offset }) {
    const { rows, count } = await this.ctx.model.HxVersions.findAndCountAll({
      attributes: { exclude: [ 'createdAt', 'updatedAt' ] },
      order: [[ 'updated_at', 'DESC' ]],
      offset,
      limit,
    })
    return { list: rows, total: count }
  }
  /**
   * 最新的版本号
   */
  async newestVersion() {
    return await this.ctx.model.HxVersions.findAll({
      attributes: { exclude: [ 'createdAt', 'updatedAt' ] },
      order: [[ 'versionName', 'DESC' ]],
      offset: 0,
      limit: 1,
    })
  }
  /**
   * 添加版本信息
   * @param { Object } body 传入的参数对象
   */
  async addPackage(body) {
    return await this.ctx.model.HxVersions.upsert(body)
  }
}
module.exports = versionManageService
原文地址:https://www.cnblogs.com/antyhouse/p/13256039.html