一只甜甜圈
2023-08-18 13:58:22
我有 2 個型號:PropertyAccountAProperty hasOne Account財產(chǎn)Property.belongsTo(models.Account, { as: 'account', foreignKey: 'accountNumber'});帳戶Account.hasOne(models.Property, { as: 'property', foreignKey: 'accountNumber'});根據(jù)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" }}然而,我的目標是實現(xiàn)這樣的目標:{ "accountNumber":"AC0012", "accountOrganisation":"Example Org", "accountEmail":"email@email.com"}當前MySQL查詢?nèi)缦拢籗ELECT `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` 我怎樣才能實現(xiàn)這個目標?這看起來很簡單,但我似乎無法查詢正確的解決方案。我可能在搜索中使用了不正確的術(shù)語,瀏覽官方文檔并沒有找到解決方案。任何幫助將不勝感激
1 回答

慕容3067478
TA貢獻1773條經(jīng)驗 獲得超3個贊
您可以使用帶有 的數(shù)組為連接列起別名[value, key],其中 value 是sequelize.col()包含的模型的值。由于您只需要原始 JSON 結(jié)果,因此您也可以傳遞raw: true而不將結(jié)果解析到模型實例,以獲得更好的性能。
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
提交
取消