I’m querying customer orders for a specified customer using Sequelize relationships.
index.js
JavaScript
x
3
1
var results2 = await customerService.getOrders(1);
2
console.log(results2);
3
service.js
JavaScript
1
11
11
1
exports.getOrders = function (id) {
2
return customerModel.findAll({
3
raw: true,
4
include: [{
5
model: orderModel,
6
where: { customer_idcustomer: id }
7
}],
8
9
}).then(r => r);
10
};
11
results
JavaScript
1
16
16
1
[ { idcustomer: 1,
2
customername: 'hello world',
3
'orders.idorder': 1,
4
'orders.orderdesc': 'order description 1',
5
'orders.customer_idcustomer': 1 },
6
{ idcustomer: 1,
7
customername: 'hello world',
8
'orders.idorder': 2,
9
'orders.orderdesc': 'Test 456',
10
'orders.customer_idcustomer': 1 },
11
{ idcustomer: 1,
12
customername: 'hello world',
13
'orders.idorder': 3,
14
'orders.orderdesc': 'Test 123',
15
'orders.customer_idcustomer': 1 } ]
16
expected
JavaScript
1
19
19
1
[ { idcustomer: 1,
2
customername: 'hello world',
3
'orders: [{
4
'orders.idorder': 1,
5
'orders.orderdesc': 'order description 1',
6
'orders.customer_idcustomer': 1 },
7
},
8
{
9
'orders.idorder': 2,
10
'orders.orderdesc': 'order description 2',
11
'orders.customer_idcustomer': 1 },
12
},
13
{
14
'orders.idorder': 3,
15
'orders.orderdesc': 'order description 3',
16
'orders.customer_idcustomer': 1 },
17
}]
18
]
19
Advertisement
Answer
All you need is to remove raw: true,
from query ,
as it will return plain/flat object , and that will convert your object as it looks now.
JavaScript
1
11
11
1
exports.getOrders = function (id) {
2
return customerModel.findAll({
3
// raw: true, // <------ Just remove this line
4
include: [{
5
model: orderModel,
6
where: { customer_idcustomer: id }
7
}],
8
9
}).then(r => r);
10
};
11
Note : You should put the where condition in upper level as per your logic
JavaScript
1
10
10
1
exports.getOrders = function (id) {
2
return customerModel.findAll({
3
where: { id: id } ,
4
// raw: true, // <------ Just remove this line
5
include: [{
6
model: orderModel
7
}]
8
}).then(r => r);
9
};
10