我的关系定义如下,
device_data.belongsTo(models.device)
device.belongsTo(models.category)
category.belongsTo(models.role)
我想要获取的是属于特定 Angular 色的所有设备数据。现在我有以下工作:
const query = {
include: [{
model: device,
attributes: ['id'],
include: [{
model: category,
attributes: ['id'],
include: [{
model: role,
attributes: ['id'],
where: {
id: {
[Op.eq]: roleId,
},
},
required: true,
}],
required: true,
}],
required: true,
}],
};
显然,这会返回如下格式的数据:
{
"id": 1,
"created_timestamp": "2019-08-12T12:28:36.194Z",
"device_id": 1,
"device_value": 0,
"initiator_id": 2,
"device": {
"id": 1,
"category": {
"id": 1,
"role": {
"id": 1
}
}
}
},
role
嵌套在第 3 层,role.id
嵌套在第 4 层。
我想要实现的是:
{
"id": 1,
"created_timestamp": "2019-08-12T12:28:36.194Z",
"device_id": 1,
"device_value": 0,
"initiator_id": 2,
"device": 1,
"category": 1,
"role": 1
},
如果有人能给我一个提示或可能的查询以从 sequelize 生成这样的数据,我将不胜感激。非常感谢。
最佳答案
要禁用模型嵌套,请在 query 中使用
raw: true
.要删除表名前缀,请将属性重新定位到您的顶级模型,但添加表别名。
例如:
TopModel.find(
raw: true,
attributes :
[
'id', 'created_timestamp', // from main table
'device.id' // from included table
],
include [{
model: device,
attributes: [], // nothing at this level
}]
)
// etc, etc,
我只是猜测 device
是表的别名。如果您收到一条错误消息(大致)“字段不存在”,请查阅生成的 SQL 以获得正确的别名。
关于javascript - Sequelize : how to get flattened data, 基于嵌套关联加入表时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60589495/