我要删除类数据中的class_teacher
。
我尝试通过attributes
字段来排除class_teacher
。但这是行不通的。
我还有尝试
const classes = await Teacher.findOne({
where: {
id: 1
},
include: [{
model: Class,
through: {
attributes: []
}
}]
})
那是可行的〜但是我想知道还有另一种方法可以实现它。
共有三个模型,分别名为Teacher and Class和ClassTeacher
sequelize.define('class', {
id: {
type: dataTypes.BIGINT(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
unique: true,
comment: 'class id',
},
name: {
type: dataTypes.STRING,
allowNull: false,
comment: 'class name'
}
})
sequelize.define('teacher', {
id: {
type: dataTypes.BIGINT(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
unique: true,
comment: 'teacher id',
},
name: {
type: dataTypes.STRING,
allowNull: false,
comment: 'teacher name'
}
})
sequelize.define('class_teacher', {
id: {
type: dataTypes.BIGINT(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
unique: true,
comment: 'association id',
}
})
协会
Class.belongsToMany(Teacher, {
through: ClassTeacher
});
Teacher.belongsToMany(Class, {
through: ClassTeacher
});
现在我要查询ID为1的老师
// get the teacher
const teacher = await Teacher.findByPk(1);
// get classes of this teacher
const classes = teacher.getClasses()
ctx.body = {classes}
让我们看一下Koa反应的数据
{
"classes": [
{
"id": 1,
"name": "grade one",
"createdAt": "2019-05-15T09:53:35.000Z",
"updatedAt": "2019-05-15T09:53:35.000Z",
"deletedAt": null,
"class_teacher": {
"id": 1,
"createdAt": "2019-05-15T09:53:35.000Z",
"updatedAt": "2019-05-15T09:53:35.000Z",
"deletedAt": null,
"classId": 1,
"teacherId": 1
}
},
{
"id": 2,
"name": "grade two",
"createdAt": "2019-05-16T10:48:14.000Z",
"updatedAt": "2019-05-16T10:48:15.000Z",
"deletedAt": null,
"class_teacher": {
"id": 4,
"createdAt": "2019-05-16T02:48:19.000Z",
"updatedAt": "2019-05-16T02:48:19.000Z",
"deletedAt": null,
"classId": 2,
"teacherId": 1
}
}
]
}
不是我要删除的class_teacher
字段。
我可以这样做吗?
预期数据
{
"classes": [
{
"id": 1,
"name": "grade one",
"createdAt": "2019-05-15T09:53:35.000Z",
"updatedAt": "2019-05-15T09:53:35.000Z",
"deletedAt": null
},
{
"id": 2,
"name": "grade two",
"createdAt": "2019-05-16T10:48:14.000Z",
"updatedAt": "2019-05-16T10:48:15.000Z",
"deletedAt": null
}
]
}