首页 > 解决方案 > 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 },   
    }]
]

标签: javascriptnode.jssequelize.js

解决方案


您只需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);
};

推荐阅读