gpt4 book ai didi

node.js - 在 toJSON sequelize 中自定义返回的外键对象

转载 作者:行者123 更新时间:2023-12-03 22:33:42 25 4
gpt4 key购买 nike

我有 user 对象,它具有来自 parentUser 的外键。它返回如下。

user:{
id:1,
profilePicture: "",
dateOfBirth: "",
parentUser:{
name: "John Doe",
email: "john@example.com",
}
}
我需要的是返回对象如下:
user:{
id:1,
profilePicture: "",
dateOfBirth: "",
name: "John Doe",
email: "john@example.com",
}

最佳答案

您可以使用 parentUser 选项为 attributes 字段创建别名,如下所示:

const user = await db.User.findOne({
where: {
id: userId
},
attributes: ['id', 'profilePicture', 'dateOfBirth', [sequelize.col('parentUser.name'), 'name'], sequelize.col('parentUser.email'), 'email']]
}),
include: [{
model: ParentUser,
as: 'parentUser',
attributes: []
}]

关于node.js - 在 toJSON sequelize 中自定义返回的外键对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64016068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com