如何在sequelize中对嵌套模型中的列进行排序?
Posted
技术标签:
【中文标题】如何在sequelize中对嵌套模型中的列进行排序?【英文标题】:How to order columns in nested models in sequelize? 【发布时间】:2018-10-22 17:37:07 【问题描述】:我正在尝试使用列startAt 以asc 顺序检索scheduled_class 模型。 模型的关联如下。
scheduled_class : class=> m:1 班级:老师 => 1:1 类:scheduled_class=> 1:m我首先在数据库中查询 schedule_class,然后包括与模型关联的类,然后包括与类模型关联的所有计划类,它们属于给定范围。我能够在不订购数据的情况下检索数据。当我添加 order 属性以进行续集时,它会出现以下错误。如何按照列startsAt 的asc 顺序检索预定的课程? `
"message":"'order clause' 中的未知列 'class.name'","code":500,"className":"general-error","data":
module.exports = function ()
return function (context)
const sequelize = context.app.get('sequelizeClient');
context.params.sequelize =
raw: false,
include: [ model: sequelize.models.attendance, paranoid: true ],
order: []
;
if(context.params.query && context.params.query.includeClasses)
let startDate = new Date();
startDate.setMonth(startDate.getMonth() -1);
startDate.setDate(1);
let endDate = new Date();
endDate.setMonth(endDate.getMonth() + 2);
endDate.setDate(0);
context.params.sequelize.include.push(
model: sequelize.models.classes,
paranoid: true,
include:[
model:sequelize.models.teacher,
paranoid: true
,
model:sequelize.models.scheduled_class,
paranoid: true,
where:
startsAt:
$gte: startDate
,
endsAt:
$lte: endDate
,
,
],
order: [[sequelize.models.teacher, 'id', 'DESC']]
);
context.params.sequelize.order.push([sequelize.models.classes, 'name', 'DESC']);
//context.params.sequelize.order.push([sequelize.models.teacher, 'id', 'DESC']);
//context.params.sequelize.order.push([sequelize.models.scheduled_class, 'startsAt', 'DESC']);
delete context.params.query.includeClasses;
;
;
【问题讨论】:
【参考方案1】:我能够通过将父模型添加到 order 子句来解决问题。
module.exports = function ()
return function (context)
const sequelize = context.app.get('sequelizeClient');
context.params.sequelize =
raw: false,
include: [ model: sequelize.models.attendance, paranoid: true ],
order: []
;
if(context.params.query && context.params.query.includeClasses)
let startDate = new Date();
startDate.setMonth(startDate.getMonth() -1);
startDate.setDate(1);
let endDate = new Date();
endDate.setMonth(endDate.getMonth() + 2);
endDate.setDate(0);
context.params.sequelize.include.push(
model: sequelize.models.classes,
paranoid: true,
include:[
model:sequelize.models.teacher,
paranoid: true
,
model:sequelize.models.scheduled_class,
paranoid: true,
where:
startsAt:
$gte: startDate
,
endsAt:
$lte: endDate
,
,
],
);
context.params.sequelize.order.push([sequelize.models.classes, sequelize.models.scheduled_class, 'startsAt', 'ASC']);
delete context.params.query.includeClasses;
;
;
在这里包含 class=> scheduled_class 模型后,我通过 schedule_class.startsAt ASC 将订单推送到订单数组。
【讨论】:
以上是关于如何在sequelize中对嵌套模型中的列进行排序?的主要内容,如果未能解决你的问题,请参考以下文章