我在Sequelize.js
中定义了两个数据库模型:
用户:
module.exports = (sequelize, DataTypes) => {
const model = sequelize.define('User', {
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false
},
password: {
type: DataTypes.CHAR,
length: 60,
allowNull: false
}
}
});
model.associate = models => {
model.belongsToMany(models.Role, {
hooks: true,
through: 'user_roles'
})
};
return model;
};
角色:
module.exports = (sequelize, DataTypes) => {
const model = sequelize.define('Role',
{
name: {
type: DataTypes.STRING,
unique: false,
allowNull: false
}
}
);
model.associate = models => {
model.belongsToMany(models.User, {
hooks: true,
through: 'user_roles'
});
};
return model;
};
表user_roles
是自动创建的。当我查询User
时,我也想在结果中包含roles
数组。我是这样的:
const user = await User.findOne({
where: {
email: data.email
},
attributes: ['id', 'password', 'email'],
include: [{
model: 'user_roles',
attributes: ['key']
}]
});
但是我收到错误消息:TypeError: include.model.getTableName is not a function
意味着model:
必须是真实模型,不能仅使用表名。但是如何从该表中获取数据呢?
我也尝试过:
const user = await User.findOne({
where: {
email: data.email
},
attributes: ['id', 'password', 'email'],
include: [{
model: Role,
attributes: ['key']
}]
});
但这给我带来了太多数据的奇怪对象:
Roles: [
{
key: 'USER',
user_roles: {
createdAt: 2019-09-17T16:19:44.000Z,
updatedAt: 2019-09-17T16:19:44.000Z,
RoleId: 1,
UserId: 4
}
}
]
我只需要key: 'USER'
答案 0 :(得分:0)
尝试添加through: { attributes: [] }
。
const user = await User.findOne({
where: {
email: data.email
},
attributes: ['id', 'password', 'email'],
through: { attributes: [] },
include: [{
model: Role,
attributes: ['key']
}]
});