无法在sequalize中关联表(节点js + sequalize)

时间:2018-02-19 21:00:52

标签: node.js express sequelize.js

我有两个结构如下的表:

FeedPost id,text,likecount,commentcount

注释 id,text,lkpfeedpostid

因此,通过lkpfeedpostid评论feedpost是一个外键。所以一个FeedPost可以有很多评论。我正在尝试将其设置为sequalize,这样当我执行FeedPost.findAll()时,它会将所有注释的Feed帖子拉回来。

以下是我如何设置它:

模型定义:

FeedPost:

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!

1 个答案:

答案 0 :(得分:2)

我假设您的续集版本> = 4。

classMethodsinstanceMethods已被删除。可以在此处找到更改日志:Sequelize V4 Breaking Changes

docs开始,您可以参考当前方法来指定关联。

FeedPost

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' }]})