我有以下两种模式:
module.exports = function(sequelize, DataTypes) {
var ChatRoom = sequelize.define('ChatRoom', {
status: DataTypes.STRING,
}, {
classMethods: {
associate: function(models) {
ChatRoom.hasMany(models.User)
ChatRoom.hasMany(models.Message)
}
}
});
return ChatRoom;
};
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
friendly_id: DataTypes.STRING,
}, {
classMethods: {
associate: function(models) {
User.hasMany(models.Message)
}
}
});
return User;
};
当我提取用户时,我也希望获取关联的ChatRoom
。我尝试了以下
models.User.findOne({
where: {messenger_id: senderID},
include: [{model: models.ChatRoom}]
}).then(function(user) { ... })
但是我收到了这个错误
ChatRoom is not associated to User!
答案 0 :(得分:0)
定义ChatRoom
模型时,您还应将此模型与associate
模型相关联。
我不了解您的业务逻辑,但我认为User
模型的associate: function(models) {
User.hasMany(models.Message);
User.belongsTo(models.ChatRoom, {
onDelete: "CASCADE",
foreignKey: {
allowNull: false
}
});
}
方法应如下所示:
{{1}}