2017-02-16 25 views
0

我對型號用戶如何從Sequelize中的輸出中刪除關聯?

// model user.js 
classMethods: { 
    associate: function(models) { 
     User.belongsToMany(models.project, {through: 'user_project', foreignKey: 'user_id', otherKey: 'project_id'}) 
    } 
} 

定義從路線表達我然後查詢該用戶的項目,並將其輸出作爲JSON

user.getProjects({ 
    attributes: ['id', 'title'], 
}) 
.then(function(projects) { 
    res.json(projects) 
}) 

這工作得很好,除了一類方法事實上輸出還包含user_project財產,我想隱藏/省略/刪除

[ 
    { 
    "id": 8, 
    "title": "Some project", 
    "user_project": { 
     "created_at": "2017-02-16T22:52:48.000Z", 
     "updated_at": "2017-02-16T22:52:48.000Z", 
     "project_id": 8, 
     "user_id": 5 
    } 
    }, 
    //etc. 

我曾嘗試過各種exclu de和include語句,但輸出始終包含它。

有沒有辦法讓這個顯示在輸出中?

回答

1

你應該嘗試以下

user.getProjects({ 
    attributes: ['id', 'title'], 
    through: { 
     attributes: [] 
    } 
}) 
.then(function(projects) { 
    res.json(projects) 
}) 
+0

我試過這種方式,但它仍然顯示'user_project'作爲響應的一部分。 – Hyra

+0

有趣的是,當我升級到[email protected]它應該工作,但'getProjects'沒有定義。 – Hyra

1

我偶然發現瞭解決方案。

要從連接表的屬性,你可以使用joinTableAttributes,像這樣:

user.getProjects({ 
    attributes: ['id', 'title'], 
    joinTableAttributes: [] 
}) 
.then(function(projects) { 
    res.json(projects) 
}) 

通過這樣做,它會刪除user_project表(見OP)輸出,其結果是:

[ 
    { 
    "id": 8, 
    "title": "Test Project", 
    }, 
    { 
    "id": 4, 
    "title": "Another one", 
    } 
] 
+0

酷,很高興知道 –

+1

必須承認它很好地隱藏在續集文檔中,只有關於'joinTableAttributes'的單個句子;) – piotrbienias