我有以下代码使用sequelize和mySQL数据库编写:
return await SelectedEmployees.findAndCountAll({
attributes: ['organization_id'],
include: [
{
model: User,
as: 'user',
attributes: ['id', [sequelize.literal(`CONCAT(user.first_name, ' ', user.last_name)`), 'name'], 'email'],
where: {
'email': {
[Op.like]: `%${search}%`
}
}
}
],
where: {
courseId: course_id,
},
});
通过上面的代码,我得到了如下的响应:
{
"count": 3,
"rows": [
{
"organization_id": 101023,
"user": [
{
"id": 1,
"name": "User One",
"email": "userOne@email.com"
}
]
},
{
"organization_id": 101023,
"user": [
{
"id": 2,
"name": "User Two",
"email": "userTwo@email.com"
}
]
},
{
"organization_id": 957256,
"user": [
{
"id": 3,
"name": "User Three",
"email": "userThree@email.com"
}
]
}
]
}
但是,可以看到,对于每个user
对象,它是作为对象数组返回的,而不仅仅是返回一个对象。我的目标是简化对象并得到以下输出:
{
"count": 3,
"rows": [
{
"organization_id": 101023,
"id": 1,
"name": "User One",
"email": "userOne@email.com"
},
{
"organization_id": 101023,
"id": 2,
"name": "User Two",
"email": "userTwo@email.com"
},
{
"organization_id": 957256,
"id": 3,
"name": "User Three",
"email": "userThree@email.com"
}
]
}
我尝试使用raw: true
和nest: true
,但得到的结果略有不同,id
,name
和email
字段位于user对象下面,如下所示:
{
"organization_id": 101023,
"user": {
"id": 1,
"name": "User One",
"email": "userOne@email.com"
}
},
1条答案
按热度按时间jmp7cifd1#
nest: true
意味着你想嵌套它(放入一个对象中)。这就是为什么在user
对象下得到name
和email
。看看您的预期结果,您不想嵌套,因此是
raw: true; nest: false
,但是,这会导致Sequelize将添加关联/表名称作为属性名称的前缀(我认为这是为了避免在有多个包含时发生命名冲突)。
如果要控制展平对象中这些属性的命名,则需要在顶层添加
attributes
选项。这将导致