2 回答
TA贡献1860条经验 获得超8个赞
findAll()是一个异步函数,它返回一个Promise。您需要使用.then()来获得结果并在那里执行转换。
db.SalesRep.findAll({
attributes: ['id', 'name', 'email'],
include: [{
model: db.Customers,
as: 'customers',
}],
where: {'id': "1"},
order: orderClause,
offset,
limit,
}).then(function(users) {
let sales_rep = users.sales_rep;
for (let key in sales_rep) {
sales_rep[key].customers = sales_rep[key].customers.length;
}
// do more stuff with users
});
TA贡献1856条经验 获得超5个赞
let data = {
"sales_rep": {
"1": {
"id": 1,
"name": "Joe",
"email": "joebloggs@email.com",
"customers": [
{
"id": 1,
"address": "1 High Street",
"name": "CUSTOMER1",
"supplierId": 1,
},
{
"id": 2,
"address": "2 High Street",
"name": "CUSTOMER2",
"supplierId": 1,
},
{
"id": 3,
"address": "3 High Street",
"name": "CUSTOMER3",
"supplierId": 1
},
]
}
}
}
let customerCount = data.sales_rep['1'].customers.length
Object.assign(data.sales_rep['1'], { customers: customerCount})
console.log(data)
db.SalesRep.findAll方法是重现承诺,因此您可以await用来获取结果
let users = await db.SalesRep.findAll({
attributes: ['id', 'name', 'email'],
include: [{
model: db.Customers,
as: 'customers',
}],
where: {'id': "1"},
order: orderClause,
offset,
limit,
})
let sales_rep = users.sales_rep;
for (let key in sales_rep) {
sales_rep[key].customers = sales_rep[key].customers.length;
}
添加回答
举报