这适用于我的模型和关系。
/* the models in the array are declared on the basis of relationships */
var models = [
'User',
'State',
'Party',
'Politician',
'Constituency',
'Award',
'Comment',
'Favorite',
'Rating'
];
models.forEach(function(model) {
//need to drop things to make sure the order is maintained while droping tables...
module.exports[model] = sequelize.import(__dirname + '/' + model);
});
/*** setup relationships ***/
(function(m) {
m.Award.belongsTo(m.Politician, {foreignKey: 'award_politician_id',
as: 'politician_id',foreignKeyConstraint:true});
m.Politician.hasMany(m.Award, {foreignKey: 'award_politician_id',foreignKeyConstraint:true});
m.Comment.belongsTo(m.User, {foreignKey: 'comment_user_id',
as: 'user_id',foreignKeyConstraint:true});
m.Comment.belongsTo(m.Politician, {foreignKey: 'comment_politician_id',
foreignKeyConstraint:true});
m.Politician.hasMany(m.Comment, {foreignKey: 'comment_politician_id',
foreignKeyConstraint:true});
m.User.hasMany(m.Comment, {foreignKey: 'comment_user_id',
foreignKeyConstraint:true});
m.Favorite.belongsTo(m.User, {foreignKey: 'favorite_user_id',
as: 'user_id',foreignKeyConstraint:true});
m.Favorite.belongsTo(m.Politician, {foreignKey: 'favorite_politician_id',
as: 'politician_id',foreignKeyConstraint:true});
m.Politician.hasMany(m.Favorite,{foreignKey: 'favorite_politician_id',
foreignKeyConstraint:true});
m.User.hasMany(m.Favorite, {foreignKey: 'favorite_user_id',
foreignKeyConstraint:true});
m.Rating.belongsTo(m.User, {foreignKey: 'rating_user_id',
as: 'user_id',foreignKeyConstraint:true});
m.Rating.belongsTo(m.Politician, {foreignKey: 'rating_politician_id',
as: 'user_id',foreignKeyConstraint:true});
m.Politician.hasMany(m.Rating, {foreignKey: 'rating_politician_id',
foreignKeyConstraint:true}
);
m.User.hasMany(m.Rating, {foreignKey: 'rating_user_id',
foreignKeyConstraint:true}
);
m.Constituency.belongsTo(m.State, {foreignKey: 'constituency_state_id',
as: 'state_id',foreignKeyConstraint:true});
m.State.hasMany(m.Constituency,{foreignKey: 'constituency_state_id', foreignKeyConstraint:true});
m.Politician.belongsTo(m.Party, { foreignKey: 'politician_party_id',
as: 'party_id',
foreignKeyConstraint:true});
m.Party.hasMany(m.Politician, {foreignKey: 'politician_party_id', foreignKeyConstraint:true});
// m.User.drop();
//
// sequelize.sync();
})(module.exports);
/** drop existing relationships manually in reverse order**/
models.reverse().forEach(function(model) {
sequelize.import(__dirname + '/' + model).drop().success(function(){
console.log("success model:" + model);
}).error(function(error){
console.log("model:" + model + " error:" + error);
});
});
/** sync **/
sequelize.sync();