2017-03-16 74 views
0

使用sequelize,我們無法執行包含來自其他模型(Player)的字段的查詢,而不包括模型的名稱作爲屬性。無法刪除Sequelize查詢中的模型屬性

我們想獲得這樣的結果(看每個對象的最後一個屬性:號碼):

[ { id: '35', 
    username: '4f224bd78d1a943ead9db2f73991e93dc8227335', 
    firstName: '8c81f070b9adad3d3693', 
    lastName: 'f9f5792d8a827e83974b', 
    email: '[email protected]', 
    created_at: '2017-03-16T07:35:15.676Z', 
    updated_at: '2017-03-16T07:35:15.676Z', 
    deleted_at: null, 
    number: null }, 

{ id: '36', 
    username: '613400c032540519fce322f4aa6abdb082834005', 
    firstName: '8bbc5692042ea4ce06f6', 
    lastName: 'b26d6701c275e07e1ea1', 
    email: '[email protected]', 
    created_at: '2017-03-16T07:35:15.768Z', 
    updated_at: '2017-03-16T07:35:15.768Z', 
    deleted_at: null, 
    number: 10 } ] 

相反,我們得到這樣的:

[ { id: '35', 
    username: '4f224bd78d1a943ead9db2f73991e93dc8227335', 
    firstName: '8c81f070b9adad3d3693', 
    lastName: 'f9f5792d8a827e83974b', 
    email: '[email protected]', 
    created_at: '2017-03-16T07:35:15.676Z', 
    updated_at: '2017-03-16T07:35:15.676Z', 
    deleted_at: null, 
    Player: { number: null } }, 
{ id: '36', 
    username: '613400c032540519fce322f4aa6abdb082834005', 
    firstName: '8bbc5692042ea4ce06f6', 
    lastName: 'b26d6701c275e07e1ea1', 
    email: '[email protected]', 
    created_at: '2017-03-16T07:35:15.768Z', 
    updated_at: '2017-03-16T07:35:15.768Z', 
    deleted_at: null, 
    Player: { number: 10 } } ] 

我們有4個型號參與:用戶(幾乎所有的屬性),播放器(有數字),角色(包含角色)和UserRole(關聯用戶和角色)。

async function getPlayers() { 
    const playerRole = await sequelize.models.Role.getPlayerRole();  

    return sequelize.models.User.findAll({ 
    include: [{ 
     association: sequelize.models.User.hasOne(sequelize.models.UserRole), 
     model: sequelize.models.UserRole, 
     where: { 
     club_id: this.clubId, 
     team_id: this.id, 
     role_id: playerRole.id 
     } 
    }, { 
     association: sequelize.models.User.hasOne(sequelize.models.Player), 
     model: sequelize.models.Player, 
     where: { 
     team_id: this.id, 
     }, 
     attributes: ['number'] 
    }] 
    }); 
} 

回答

1

可以使用sequelize.col(),但很可能需要添加raw: truefindAll呼叫,因爲否則結果將被轉換爲User模型實例,所以number屬性會被忽略反正。

return sequelize.models.User.findAll({ 
    attributes: { include: sequelize.col('Player.number') }, 
    raw: true, // added to prevent returning User instances from the query, only simple JSON data 
    include: [ 
     { 
      model: sequelize.models.UserRole, 
      where: { 
       club_id: this.clubId, 
       team_id: this.id, 
       role_id: playerRole.id 
      } 
     }, 
     { 
      model: sequelize.models.Player, 
      where: { 
       team_id: this.id, 
      }, 
      attributes: [] 
     } 
    ] 
}); 

我已刪除了association屬性 - 我假設你已經宣佈他們在模型定義,所以沒有必要在他們每次都同時做查詢。

必須在Sequelize實例上調用col()方法。

+0

已解決。感謝您的快速和完整的迴應。 –