[英]How to pass query params into sequelize when params describe relations
For instance, I have model Student
and a couple of models that relates to it. 例如,我有
Student
模型和几个与此模型相关的模型。 Let it be Class
, Absence
and Grade
. 让它成为
Class
, Absence
和Grade
。
Definitions for this models: 该模型的定义:
var Student = sequelize.define('Student', {
class_id : DataTypes.INTEGER,
name : DataTypes.INTEGER,
gender : DataTypes.ENUM('male', 'female')
is_paid : DataTypes.BOOLEAN
})
var Class = sequelize.define('Class', {
name : DataTypes.STRING
})
var Absense = sequelize.define('Absense', {
student_id : DataTypes.INTEGER
date : DataTypes.DATEONLY,
})
var Grade = sequelize.define('Grade', {
student_id :
subject : DataTypes.ENUM('singing', 'dancing')
value : DataTypes.INTEGER
})
Absense.belongsTo(Student, { foreign_key : 'student_id' });
Grade.belongsTo(Student, { foreign_key : 'student_id' })
I want to add endpoint to list entities for this model. 我想添加端点以列出该模型的实体。 But also I want to allow to use optional filters in this endpoint.
但我也想允许在此端点中使用可选过滤器。 So both of this usages will be possible:
因此,这两种用法都是可能的:
GET api.acme.com/v0.1/users
GET api.acme.com/v0.1/users? class=1,3 &gender=male &is_paid=true &absences=true &avg_grade=gt:3 &limit=20&offset=0&order=avg_grade%20DESC
While I handle params that present in Student
, it's easy: 当我处理
Student
中存在的参数时,很简单:
var condition = {};
req.params.is_paid && condition.is_paid = boolean(req.params.is_paid);
req.params.gender && condition.gender = { $in : req.params.gender.split(',') };
req.params.class && condition.class = { $in : req.params.class.split(',') };
res.json(await Student.findAll({
where : condition,
limit : req.query.limit || 20,
offset : req.query.offset || 0,
order : req.query.order || 'id ASC'
}))
But when I want to add implement absense
or avg_grade
filter, I have to step down from sequelize and write raw query for this that turns to be huge. 但是,当我要添加实施
absense
或avg_grade
过滤器,我必须从sequelize下台,及写这变成是巨大的原始查询。
Right now I'm thinking about creating special students_expanded
view for this, but I want to be sure, I'm not missing anything. 现在,我正在考虑为此创建特殊的
students_expanded
视图,但我想确定的是,我没有丢失任何内容。 Is there any way to do this using Sequelize? 有什么办法可以使用Sequelize做到这一点吗?
Add an include
object with the requested model and filter and set required: true
on it. 添加
include
请求的模型和过滤器的include
对象,并将其设置为required: true
。
The following would show all students with an absence: 以下内容将显示所有缺勤的学生:
Student.findAll({
where : condition,
limit : req.query.limit || 20,
offset : req.query.offset || 0,
order : req.query.order || 'id ASC'
include: {
model: Absense,
required: true
}
}))
The average grade is trickier, because you need to aggregate the grades to get the average - see Average of grouped data in column using Sequelize 平均成绩比较棘手,因为您需要汇总成绩才能得出平均值-请参见使用Sequelize列中的分组数据的平均值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.