使用sequelize進行列表排序
阿新 • • 發佈:2020-07-06
官方文件: 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