我有两个结构如下的表:
饲料邮局
id、文本、赞数、评论数
评论
ID,文本,lkpfeedpostid
所以有一个通过lkpfeedpostid从评论到feedpost的外键。所以一个 FeedPost 可以有很多评论。我试图在 sequalize 中设置它,以便当我执行 FeedPost.findAll() 时,它会拉回包含所有评论的提要帖子。
这是我设置的方式:
模型定义:
饲料邮政:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('FeedPost', {
...
...
}, {
tableName: 'FeedPost',
classMethods: {
associate : function(models) {
FeedPost.hasMany( Comment, { as: 'comments' });
},
},
});
};
评论:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Comment', {
...
...
}, {
tableName: 'Comment',
classMethods: {
associate : function(models) {
Comment.belongsTo(FeedPost, { foreignKey: 'lkpfeedpostid'})
},
},
});
};
我正在导入它们,例如:
const FeedPost = sequelize.import('../models/FeedPost');
const Comment = sequelize.import('../models/Comment');
并将它们传递到快速路由器中,例如:
app.use(feed(FeedPost, Comment));
module.exports = (FeedPost, Comment) => {
const api = Router();
api.get('/api/feed', (req, res) => {
FeedPost.findAll( { include: [ {model: Comment, as: 'Comment' }]}).then(results => {
res.json({results});
});
}
我已经尝试了在这些链接中发现的大量变体:
每当我到达路线时,我都会收到错误消息
Unhandled rejection SequelizeEagerLoadingError: Comment is not associated to Feed!
最佳答案
我假设你的 Sequelize 版本> = 4。classMethods
和 instanceMethods
已被删除。可以在这里找到变更日志:Sequelize V4 Breaking Changes
从他们的 docs 你可以引用当前的方法来指定关联。
饲料邮局
module.exports = function(sequelize, DataTypes) {
const FeedPost = sequelize.define('FeedPost', {/*Attributes here*/});
FeedPost.hasMany(Comment, { as: 'comments' })
};
评论
module.exports = function(sequelize, DataTypes) {
const Comment = sequelize.define('Comment', {/*Attributes here*/});
Comment.BelongsTo(Comment, { foreignKey: 'lkpfeedpostid', targetKey: 'id' })
};
以下查询应该有效:
FeedPost.findAll( { include: [ {model: Comment, as: 'comments' }]})
关于node.js - 无法在 sequelize 中关联表( Node js + sequelize),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48874101/