使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM