Sequelize:使用.findAll获取特定列并包含

时间:2017-10-20 13:48:40

标签: javascript mysql node.js sequelize.js

我正在尝试从1到多个关系对象中仅获取特定字段。

以下是我的代码:

 db.User.findAll({
            where: {
                id: ids
            },
            include: [{
                model: db.Common,
                as: 'color',
                through: {
                    attributes: ['color']
                }
            }]
        }).then((users) => {

用户与Common表格有1米的关联。我希望只有color字段作为color返回User对象,即数组中返回的对象需要:

 users.id
 user.name
 user.color

使用上面的代码,我收到以下错误:

Unhandled rejection Error: Common (color) is not associated to User!

我做错了什么?

更新

协会

Model: User
    tableName: 'Users',
    classMethods: {
        associate: function (models) {
            User.hasMany(models.Common, {
                    as: 'common',
                    foreignKey: 'user_id'
                });
        }
})



Model: Common
tableName: 'Common',
classMethods: {
    associate: function (models) {
        AppCommon.belongsTo(models.User, {
            foreignKey: {
                name: 'user_id',
                allowedNull: false

            }
        })
    }
}

0 个答案:

没有答案