我正在使用sails.js和sequelize.js ORM。这就是我如何定义模型以使用关联: https://github.com/KSDaemon/sails-hook-sequelize
模型用户:
module.exports = {
attributes: {
user_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
username: Sequelize.STRING,
password: Sequelize.STRING,
createdAt: Sequelize.DATE,
},
associations: function () {
Response.hasMany(Post, { as: 'posts', foreignKey: 'user_id' });
Response.hasMany(Response, { as: 'responses', foreignKey: 'user_id' });
},
defaultScope: function () {
return {
include: [
{ model: Post, as: 'posts' },
{ model: Response, as: 'responses' },
]
};
},
options: {
freezeTableName : false,
tableName : 'users',
schema : 'codigomx',
classMethods : {},
instanceMethods : {},
hooks : {}
}
};
和我的模特回应:
module.exports = {
attributes: {
response_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
response_content: Sequelize.TEXT,
createdAt: Sequelize.DATE
},
associations: function () {
Response.belongsTo(User, { foreignKey: 'user_id', targetKey: 'user_id'});
Response.belongsTo(Post, { foreignKey: 'post_id', targetKey: 'post_id'});
},
options: {
freezeTableName : false,
tableName : 'responses',
schema : 'codigomx',
classMethods : {},
instanceMethods : {},
hooks : {}
}
};
但是当我尝试运行时:
User.findOrCreate({where: {username: 'user'}, defaults: {password: 'psw'}});
它给了我这个错误:未处理的拒绝SequelizeEagerLoadingError:响应与用户没有关联!
我确实有正确的关联,有人可以告诉我,如果我的协会有问题吗?
答案 0 :(得分:1)
我认为用户模型中存在拼写错误。
而不是Response.hasMany(Post, { as: 'posts', foreignKey: 'user_id' });
,应该是User.hasMany(Post, { as: 'posts', foreignKey: 'user_id' });