gpt4 book ai didi

node.js - Sequelize 关联不起作用

转载 作者:行者123 更新时间:2023-12-03 22:28:12 25 4
gpt4 key购买 nike

我有两个模型发布和评论。一个帖子可以有很多评论,一个评论可以属于一个帖子。这是使用 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)
})

最佳答案

首先需要处理拒绝,防止出现未处理的拒绝错误:

models.comment.findOne({
include: [
{
model: models.post
}
]
}).then(function (comment) {
console.log(comment)
}).catch(function (error) {
console.log(error);
});

以及关于错误描述 "post is not associated to comment" 。看起来你放错了实例。也许你需要发表评论而不是整篇文章:
include: [
{
model: models.post.comment
}
]

关于node.js - Sequelize 关联不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44783942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com