2017-02-16 465 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