我正在将Sequelize与MYSQL一起使用并表达。 尝试使用include从相关模型中选择数据时,出现 SequelizeEagerLoadingError:角色未与用户关联。
我有两个模型,用户模型和角色模型。一个用户通过RoleUser属于SubjectToMany角色,一个Role通过RoleUser属于UsersToMany用户。这是我的模特:
//用户模型
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {type:DataTypes.UUID,allowNull:false,unique:true,primaryKey:true},
UserName: {type:DataTypes.STRING,unique:true,allowNull:false},
Email: {type:DataTypes.STRING,allowNull:false,unique:true,validate: { isEmail: {msg: "Invalid Email"} }},
Password: {type:DataTypes.STRING,allowNull:false},
}, {});
User.associate = function(models) {
User.belongsToMany(models.Role,
{
through: 'RoleUser',
foreignkey:'UserId'
})
};
return User;
};
//Role Model
'use strict';
module.exports = (sequelize, DataTypes) => {
const Role = sequelize.define('Role', {
id: {type:DataTypes.UUID,allowNull:false,unique:true,primaryKey:true},
Name: DataTypes.STRING,
Description: DataTypes.STRING
}, {});
Role.associate = function(models) {
Role.belongsToMany(models.User,
{
through:'RoleUser',
foreignKey:'RoleId'
}),
};
return Role;
};
//My query on user model
xports.index = function(req, res) {
return User.findAll({
include: [{
model: Role,
}],
attributes:{
exclude: ['Password','createdAt','updatedAt']
}}).then((users)=>{
console.log(users)
}).catch(error=>{
console.log(error);
})
//错误
SequelizeEagerLoadingError: Role is not associated to User!
**STATUS CODE: 200(OK)**
I am getting same error in other models in the entire project. According to me the associations is correctly established and I can see in the PHPMyAdmin Relation View.
*Express Version: 4.16.4
Sequelize Version: 4.31.2
Mysql2 version: 1.6.1*
Any help. What am I doing wrong.
答案 0 :(得分:0)
好,因此您需要指定如何调用包含。
User.associate = function(models) {
User.belongsToMany(models.Role,{
through: 'RoleUser',
foreignkey:'UserId',
as: 'Roles'
})
};
如果需要,您需要使用其他方法将角色从角色传给用户,并与其他任何关联。然后在您的查询中:
User.findAll({
include: [{
model: Role,
as: 'Roles'
}],
attributes:{ exclude: ['Password','createdAt','updatedAt'] }
})