亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

模型包含選項可將屬性返回為具有定義別名的單個值,而不是具有屬性的對象

模型包含選項可將屬性返回為具有定義別名的單個值,而不是具有屬性的對象

一只甜甜圈 2023-08-18 13:58:22
我有 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 protected]"  }}然而,我的目標是實現這樣的目標:{   "accountNumber":"AC0012",  "accountOrganisation":"Example Org",  "accountEmail":"[email protected]"}當前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,

});


查看完整回答
反對 回復 2023-08-18
  • 1 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號