与Sequelize的一对一关系

时间:2017-04-06 00:03:37

标签: javascript node.js postgresql sequelize.js

我正在创建一个有趣的Twitter克隆,并且在Sequelize关系方面存在一些问题。

我的目标是为以下内容创建多对一关系:用户 -to- 推文

然后为以下内容创建一对一关系:推文 -to- 用户

我已经在tweet.js文件中成功完成了多对一关系,您可以在此处看到:

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Tweet = sequelize.define('Tweet', {
    tweet: DataTypes.TEXT
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        //creating a one-to-many relationship from user->tweets
        models.User.hasMany(models.Tweet, {as: 'tweets'});
      }
    }
  });
  return Tweet;
};

但是,在我的 user.js 中,我打算从以下位置创建一对一关系: Tweet -to- < em>用户,我遇到了问题。

我尝试按照文档here进行操作,但我无法成功创建此关系。以下是我当前代码的示例:

'use strict';
module.exports = function (sequelize, DataTypes) {
  var User = sequelize.define('User', {
    username: DataTypes.STRING,
    password: DataTypes.STRING
  }, {
      //classMethod guarantees the password provided by the user matches what's in the db
      classMethods: {
        associate: function (models) {
          //associate every tweet to having one author (User)
          models.Tweet.hasOne(models.User, { as: "Author" });
          models.Tweet#setAuthor(anAuthor);
        }
      }
    });
  return User;
}; //**Note that 'models' contains two objects: 'Tweet' and 'User'**

我不确定如何处理这种关系,如何从Tweet-to-User创建一对一的关系?

1 个答案:

答案 0 :(得分:0)

我想,也许这会对你有所帮助:

       module.exports = function(sequelize, DataTypes) {
            var Tweet = sequelize.define('Tweet', {
            tweet: DataTypes.TEXT
              }, {
                classMethods: {
                   associate: function(models) {
                   Tweet.belongsTo(models.User, {as: 'tweets'})
              }
           }
      });
       return Tweet;
  };



    module.exports = function (sequelize, DataTypes) {
         var User = sequelize.define('Users', {
                   username: DataTypes.STRING,
                   password: DataTypes.STRING
           }, {
    //classMethod guarantees the password provided by the user matches     what's in the db
           classMethods: {
                   associate: function (models) {
                   User.hasMany(models.Tweet, {as: "Author"})

                 }
            }
        });
           return User;
     };