javascript - Sequelize 关系查询返回重复数据
问题描述
我正在使用 Sequelize 关系查询指定客户的客户订单。
index.js
var results2 = await customerService.getOrders(1);
console.log(results2);
服务.js
exports.getOrders = function (id) {
return customerModel.findAll({
raw: true,
include: [{
model: orderModel,
where: { customer_idcustomer: id }
}],
}).then(r => r);
};
结果
[ { idcustomer: 1,
customername: 'hello world',
'orders.idorder': 1,
'orders.orderdesc': 'order description 1',
'orders.customer_idcustomer': 1 },
{ idcustomer: 1,
customername: 'hello world',
'orders.idorder': 2,
'orders.orderdesc': 'Test 456',
'orders.customer_idcustomer': 1 },
{ idcustomer: 1,
customername: 'hello world',
'orders.idorder': 3,
'orders.orderdesc': 'Test 123',
'orders.customer_idcustomer': 1 } ]
预期的
[ { idcustomer: 1,
customername: 'hello world',
'orders: [{
'orders.idorder': 1,
'orders.orderdesc': 'order description 1',
'orders.customer_idcustomer': 1 },
},
{
'orders.idorder': 2,
'orders.orderdesc': 'order description 2',
'orders.customer_idcustomer': 1 },
},
{
'orders.idorder': 3,
'orders.orderdesc': 'order description 3',
'orders.customer_idcustomer': 1 },
}]
]
解决方案
您只需raw: true,
要从查询中删除,
因为它将返回plain/flat object ,这将转换您的对象现在的样子。
exports.getOrders = function (id) {
return customerModel.findAll({
// raw: true, // <------ Just remove this line
include: [{
model: orderModel,
where: { customer_idcustomer: id }
}],
}).then(r => r);
};
注意:您应该根据您的逻辑将 where 条件放在上层
exports.getOrders = function (id) {
return customerModel.findAll({
where: { id: id } ,
// raw: true, // <------ Just remove this line
include: [{
model: orderModel
}]
}).then(r => r);
};
推荐阅读
- python-3.x - Python OOP 继承用例和调用继承对象
- git - 重置后如何强制提交作为受保护分支的新负责人?
- javascript - JS 正则表达式检查字符串仅包含锚点
- javascript - MacOS Safari 的 Highmaps downloadXLS() 问题
- formik - 使用Formik最佳实践
- rust - Rust: impl From<_> 用于 usize、u64、u32 等
- xamarin - Xamarin Carousel View:峰值时对齐当前项目中心?
- javascript - 渲染如何与分页点击状态同步?
- shell - 我自己的 shell 程序中的后台进程忽略标准输入
- javascript - 我的分页跳来跳去,我不知道如何解决它