“续集”中的一对多关系

时间:2017-01-25 22:12:36

标签: javascript node.js postgresql sequelize.js

我在创建和测试两个Sequelize模型之间的一对多关系时遇到了麻烦。用户有很多评论。

这是我的用户模型。它有一个属性:电子邮件地址。

它还有一个'associate'类方法,可以在代码中的其他位置调用。我传入数据库模型,'associate'创建模型之间的关系。

module.exports = function(sequelize, DataTypes) {
    var User = sequelize.define('User', 
    { 
        email_address: { type: DataTypes.TEXT }
    },
    { 
        classMethods: {
            associate: function(models) {
                models.User.hasMany(models.Comment);
                models.Comment.belongsTo(models.User);
            }
        }
    });
    return User;
}

这是我的评论模型。够简单......

module.exports = function(sequelize, DataTypes) {
    var Comment = sequelize.define('Comment',
    {
       text: { type: DataTypes.TEXT, allowNull: false }
    });
    return Comment;
}

然后,在其他地方,我想播种一些数据并测试关联。我是否正确地将新评论与新用户相关联?或者,有没有更好的方法来抓取我刚刚创建的用户,然后将新评论与它相关联?

播种此数据后,我想找到新用户,从用户检索新评论,并打印出文本以测试关联。

User.create({ email_address: 'helloworld@gmail.com' });
Comment.create({ text: 'Hello World', user_id: 1 });

User
  .findById(1)
  .then(function(user) { 
      console.log(user.getComments())
  });

这不起作用。具体来说,它打印以下内容:

Promise {
  _bitField: 2097152,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _boundTo: Comment }
Executing (default): SELECT "id", "text", "createdAt", "updatedAt", "UserId" FROM "Comments" AS "Comment" WHERE "Comment"."UserId" = 1;
Unhandled rejection SequelizeBaseError: column "UserId" does not exist
at Query.formatError (/Users/sherwoodcallaway/Desktop/onboarding-comments/node_modules/sequelize/lib/dialects/postgres/query.js:357:14)
at Query.<anonymous> (/Users/sherwoodcallaway/Desktop/onboarding-comments/node_modules/sequelize/lib/dialects/postgres/query.js:88:19)
at emitOne (events.js:96:13)
at Query.emit (events.js:188:7)
at Query.handleError (/Users/sherwoodcallaway/Desktop/onboarding-comments/node_modules/pg/lib/query.js:131:8)
at Connection.<anonymous> (/Users/sherwoodcallaway/Desktop/onboarding-comments/node_modules/pg/lib/client.js:180:26)
at emitOne (events.js:96:13)
at Connection.emit (events.js:188:7)
at Socket.<anonymous> (/Users/sherwoodcallaway/Desktop/onboarding-comments/node_modules/pg/lib/connection.js:121:12)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:551:20)

知道这里出了什么问题吗? TYVM&lt; 3

0 个答案:

没有答案