我有3个模型:User,Project,UserProject:
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define('User', {
title: DataTypes.STRING,
description: DataTypes.STRING
}, {
classMethods: {
associate: function (models) {
User.belongsToMany(models.Project, {
through: 'UserProject',
foreignKey: 'userId'
})
}
},
freezeTableName: true
})
return User
}
module.exports = function (sequelize, DataTypes) {
var Project = sequelize.define('Project', {
title: DataTypes.STRING,
description: DataTypes.STRING
}, {
classMethods: {
associate: function (models) {
Project.belongsToMany(models.User, {
through: 'UserProject',
foreignKey: 'projectId'
})
}
},
freezeTableName: true
})
return Project
}
module.exports = function (sequelize, DataTypes) {
var UserProject = sequelize.define('UserProject', {
userId: DataTypes.INTEGER,
projectId: DataTypes.INTEGER,
}, {
classMethods: {
},
freezeTableName: true
})
return UserProject
}
上面的代码与Sequelize的旧版本完美配合。现在我更新到Sequelize 4.3.2并且在尝试使用这些模型时出现以下错误:
未处理拒绝SequelizeEagerLoadingError:项目未与用户关联!
这有什么问题?我尝试在这里进行多对多关联,并在findAll Projects中包含用户,反之亦然。我使用MySQL作为数据库。
这是findAll-part:
function getUsersWithProjects (request, response, next) {
models.User.findAll({
include: [{
model: models.Project,
}]
});
}
答案 0 :(得分:12)
现在我找到了解决方案。显然他们已经删除了classMethods
和instanceMethods
,所以关联现在定义如下:
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define('User', {
title: DataTypes.STRING,
description: DataTypes.STRING
}, {
freezeTableName: true
})
User.associate = function (models) {
User.belongsToMany(models.Project, {
through: 'UserProject',
foreignKey: 'userId'
})
};
return User
}
来源:http://docs.sequelizejs.com/manual/tutorial/upgrade-to-v4.html