我想使用sequelize从两个关联表中以非嵌套格式读取数据。
使用这行代码:
const operator = await operatorService.findOne({ where: { id: id }, include: { model: models.Account, attributes: ["email"] }, raw: true });
我能够得到这样的东西:
operator {
Account.email: "[email protected]",
city: "Rockhill",
firstName: "Livingston",
}
我想要的是这样的东西:
operator {
email: "[email protected]",
city: "Rockhill",
firstName: "Livingston",
}
我知道它可以以不同的方式做到这一点,首先获取模型,然后获取关联的模型,最后从它们两个创建对象,但我真的需要知道是否可以只用一个函数来完成。
只需在根级别的
attributes
中使用扩展语法,并在 attributes
选项中清空 include
,如下所示:
operatorService.findOne({
where: { id: id },
attributes: {
include: [['Account.email','email']]
},
include: [{
model: models.Account,
attributes: [],
}]