在创建多对多关系后,Sequelize Node.js新功能无法正常工作
So I have two models, User and Chat. Each User can have multiple chats and each chat can have multiple users. So I created a new model called UserChat -
所以我有两个模型,用户和聊天。每个用户可以有多个聊天,每个聊天可以有多个用户。所以我创建了一个名为UserChat的新模型 -
var db = require('../db');
var Chat = require('../models/chats');
var User = require('../models/users');
var UserChat = db.connection.define("user_chat", {
id: {
type: db.Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
}
})
Chat.ChatModel.belongsToMany(User.UserModel, {through: {model: 'user_chat'}});
User.UserModel.belongsToMany(Chat.ChatModel, {through: {model: 'user_chat'}});
This creates a table in my database called user_chats and according to sequelize's documentation, I should be able to use addUser on my Chat model and addChat on my User Model,
这在我的数据库中创建了一个名为user_chats的表,根据sequelize的文档,我应该可以在我的聊天模型上使用addUser并在我的用户模型上添加addChat,
But when I try to use Chat.ChatModel.addUser(user) I get the error "addUser is not a function"
但是当我尝试使用Chat.ChatModel.addUser(用户)时,我收到错误“addUser不是函数”
This is how I declare the Chat Model and User Model -
这是我如何声明聊天模型和用户模型 -
var db = require('../db')
var Chat = db.connection.define("chat", {
chatname: {
type: db.Sequelize.STRING,
unique: true,
allowNull: false
},
creator:{
type: db.Sequelize.INTEGER,
unique: false,
allowNull: false
}
});
module.exports.ChatModel = Chat;
and then my User model (simplified) -
然后我的用户模型(简化) -
var db = require('../db')
var User = db.connection.define("user", {
username: {
type: db.Sequelize.STRING,
unique: true,
allowNull: false
},
password: {
type: db.Sequelize.STRING,
unique: false,
allowNull: false
},
});
module.exports.UserModel = User;
Now if I try to use the addUser function or any new function I should be given according to the documentation I get the error that the function still doesn't exist.
现在,如果我尝试使用addUser函数或任何新函数,我应该根据文档给出错误,该函数仍然不存在。
1 个解决方案
#1
1
So my problem was I was trying to call the methods on the actual models, but the methods get added to instances of the models. So you need to find the chat/user before using the addChat or addUser on it.
所以我的问题是我试图在实际模型上调用方法,但方法被添加到模型的实例中。因此,您需要在使用addChat或addUser之前找到聊天/用户。
更多相关文章
- Angular JS复选框 - 模型不默认为false
- 根据用户时区显示当地时间 php+javascript
- Google Maps API v3:如何设置缩放级别和地图中心到用户提交的位置
- three.js学习笔记 obj模型加载问题
- Ajax的实用技术——用户的注意力从页面的其他区域到转移选择的图
- 阻止用户在表单字段中输入
- 将(重度公式加载的)Excel电子表格转换为用户友好的网络计算器
- 用户打开一个DropDown关闭其他DropDowns
- 如何在Sencha Touch中向模型添加自定义验证规则