2014-05-09 38 views
0

我試圖創建一個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; 
}; 

回答

0

在您的用戶模型,你要創建一個模型,該模型的關聯未在該範圍內定義。在User.js中,您只能訪問未定義的用戶,而不是Book或UserBook。那是什麼導致你的錯誤。

您可以在將所有模型導入到應用程序的位置或在模型文件中通過導入要關聯的模型(循環導入的模型)來創建關聯。你的用戶模型可改爲:

module.exports = function(schema, DataTypes) { 
    var Book = schema.import(__dirname + '/book'); 
    var UserBooks = schema.import(__dirname + '/userbooks'); 
    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 }); 
    Book.hasMany(User, { foreignKey: 'book_id', through: UserBooks }); 

    return User; 
}; 

有關如何做到這一點的另一個例子,見http://sequelizejs.com/articles/express#minimal-express-app

而且,我已經移除你的代碼User.sync呼叫。同步是異步調用,而導入是同步的。這意味着你正在定義你的模型,開始將它同步到數據庫,然後返回它,然後知道它已完成同步。這意味着您可能會在創建表之前嘗試使用它創建實例。相反,您應該使用sequelize.sync一次同步所有模型,並附加回調以等待同步完成(請參閱我公佈的代碼示例鏈接)

+0

謝謝您的回答。如果我在兩種模型中都實現了你的答案(所以在用戶I中包括Book,反之亦然),我得到一個錯誤:「RangeError:超出最大調用堆棧大小」。如果我從兩個文件中刪除模式導入並根據您的鏈接使用其他解決方案(使用classMethods:{...}),我得到一個錯誤「Model1與Model2沒有關聯」 –

+0

問題已解決。您的解決方案有效另一個問題是低谷,可能與我們的下劃線相沖突。另一位開發人員更改了index.js並用下劃線替換lowerdash。現在一切正常! –

+0

很高興聽到它爲你工作。 rangeError問題是因爲您正在創建循環導入。您開始執行試圖導入書籍的用戶文件,該文件再次嘗試導入用戶,等等 –