我有 2 个型号:PropertyAccountAProperty hasOne Account财产Property.belongsTo(models.Account, { as: 'account', foreignKey: 'accountNumber'});帐户Account.hasOne(models.Property, { as: 'property', foreignKey: 'accountNumber'});根据findAll我的查询const properties = await Property.findAll({ attributes: ['accountNumber'], include: [ { model: Models.Account, as: 'account', attributes: ['organisation', 'email'], }, ]});这会为每个项目返回一个对象,例如;{ "accountNumber":"AC0012", "account":{ "organisation":"Example Org", "email":"email@email.com" }}然而,我的目标是实现这样的目标:{ "accountNumber":"AC0012", "accountOrganisation":"Example Org", "accountEmail":"email@email.com"}当前MySQL查询如下;SELECT `Property`.`id`, `Property`.`account_number` AS `accountNumber`, `account`.`account_number` AS `account.accountNumber`, `account`.`organisation` AS `account`.`organisation`, `account`.`email` AS `account.email` FROM `property_dev`.`property` AS `Property` LEFT OUTER JOIN `property_dev`.`account` AS `account` ON `Property`.`account_number` = `account`.`account_number`我需要更新使用的别名;`account`.`organisation` AS `account`.`organisation`, `account`.`email` AS `account.email` 到`account`.`organisation` AS `accountOrganisation`, `account`.`email` AS `accountEmail` 我怎样才能实现这个目标?这看起来很简单,但我似乎无法查询正确的解决方案。我可能在搜索中使用了不正确的术语,浏览官方文档并没有找到解决方案。任何帮助将不胜感激
1 回答
慕容3067478
TA贡献1773条经验 获得超3个赞
您可以使用带有 的数组为连接列起别名[value, key],其中 value 是sequelize.col()包含的模型的值。由于您只需要原始 JSON 结果,因此您也可以传递raw: true而不将结果解析到模型实例,以获得更好的性能。
const properties = await Property.findAll({
attributes: [
'accountNumber',
[sequelize.col('account.organisation'), 'accountOrganisation'],
[sequelize.col('account.email'), 'accountEmail'],
],
include: {
model: Models.Account,
as: 'account',
attributes: [],
},
raw: true,
});
添加回答
举报
0/150
提交
取消