【发布时间】:2025-12-21 03:50:17
【问题描述】:
我有两个模特发布和评论。一个帖子可以有很多评论,一个评论可以属于一个帖子。这是使用 sequelize 生成的类。
发帖
'use strict';
module.exports = function(sequelize, DataTypes) {
var post = sequelize.define('post', {
title: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
post.hasMany(models.comment)
}
}
});
return post;
};
评论
'use strict';
module.exports = function(sequelize, DataTypes) {
var comment = sequelize.define('comment', {
title: DataTypes.STRING,
body: DataTypes.STRING,
postId: DataTypes.INTEGER
}, {
classMethods: {
associate: function(models) {
comment.belongsTo(models.post)
}
}
});
return comment;
};
这里是评论迁移文件:
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('comments', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
title: {
type: Sequelize.STRING
},
body: {
type: Sequelize.STRING
},
postId: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: "posts",
key:"id"
}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('comments');
}
};
我没有从帖子到评论的关系。
然后我创建一个帖子,然后创建一个评论。稍后我检索评论并指示在收到错误时获取与评论关联的帖子:
Unhandled rejection SequelizeEagerLoadingError: post is not associated to comment!
这是我使用的代码:
// create a post object
/*
const post = models.post.build({
title: "Hello World"
})
// save a new post
post.save().then(function(newPost){
console.log(newPost)
})
*/
// create a comment
/*
const comment = models.comment.build({
title: "Comment",
body: "Body",
postId : 1
})
comment.save().then(function(newComment){
console.log(newComment)
}) */
// get the comment and also the post it belongs to
models.comment.findOne({
include: [
{
model: models.post
}
]
}).then(function(comment){
console.log(comment)
})
【问题讨论】:
标签: node.js sequelize.js