我试图创建一个Sequelize HABTM关系,但我不能把它做....我仍然收到错误消息:尝试创建HABTM连接Sequelize.js
return (tableName1.toLowerCase() < tableName2.toLowerCase()) ? (tableName1
^
TypeError: Cannot call method 'toLowerCase' of undefined
我有用户模型,书籍模型和用户书籍模型。当然,我的数据库包含一个“用户”表,“user_books”表和“books”表。
UserBooks型号:
module.exports = function(schema, DataTypes) {
var UserBooks = schema.define('UserBooks', {
}, {
tableName: 'user_books', // this will define the table's name
timestamps: false // this will deactivate the timestamp columns
});
UserBooks.sync();
return UserBooks;
};
用户模式:
module.exports = function(schema, DataTypes) {
var User = schema.define('User', {
keywords: DataTypes.STRING
}, {
tableName: 'users', // this will define the table's name
timestamps: false ,// this will deactivate the timestamp columns
syncOnAssociation:false
});
User.hasMany(Book, { foreignKey: 'user_id', through: UserBooks });
User.sync();
return User;
};
Book模型:
module.exports = function(schema, DataTypes) {
var Book = schema.define('Book', {
keywords: DataTypes.STRING
}, {
tableName: 'books', // this will define the table's name
timestamps: false ,// this will deactivate the timestamp columns
syncOnAssociation:false
});
Book.hasMany(User, { foreignKey: 'book_id', through: UserBooks });
Book.sync();
return Book;
};
谢谢您的回答。如果我在两种模型中都实现了你的答案(所以在用户I中包括Book,反之亦然),我得到一个错误:“RangeError:超出最大调用堆栈大小”。如果我从两个文件中删除模式导入并根据您的链接使用其他解决方案(使用classMethods:{...}),我得到一个错误“Model1与Model2没有关联” –
问题已解决。您的解决方案有效另一个问题是低谷,可能与我们的下划线相冲突。另一位开发人员更改了index.js并用下划线替换lowerdash。现在一切正常! –
很高兴听到它为你工作。 rangeError问题是因为您正在创建循环导入。您开始执行试图导入书籍的用户文件,该文件再次尝试导入用户,等等 –