我有一个USERS表,其中有两个主键:id和mail,Users与另一个表Contacts的关系为1:1。我想将RefreshToken表中的两个外键“导出”到邮件和ID。

用户表定义:

module.exports = function (sequelize, DataTypes) {
  const Users = sequelize.define('Users', {
    id: {
      type: DataTypes.INTEGER(11),
      autoIncrement: true,
      primaryKey: true
    },
    firstname: {
      type: DataTypes.STRING,
      allowNull: true
    },
    lastname: {
      type: DataTypes.STRING,
      allowNull: true
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      primaryKey: true
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
    classMethods: {
      associate: function (models) {
        Users.hasOne(models.RefreshToken, {foreignKey:'userId'}
      }
    },
    tableName: 'Users',
    hooks: {
      beforeCreate: user => {
        const salt = bcrypt.genSaltSync();
        user.password = bcrypt.hashSync(user.password, salt);
      }
    }
  });


RefreshToken表定义:

module.exports = function (sequelize, DataTypes) {
  const RefreshToken = sequelize.define('RefreshToken', {
    idRefreshToken: {
      type: DataTypes.INTEGER(11),
      autoIncrement: true,
      primaryKey: true
    },
    token: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    expire: {
      type: DataTypes.DATE,
      allowNull: true
    }

  }, {
    tableName: 'RefreshToken'
  });

最佳答案

我不确定是否不看您的代码就100%确定,但是我认为您要尝试的是

 db.define('user', {/* ... */});
 db.define('contact', {/* ... */});

 db.model('contact').belongsTo(db.model('user'), { as: 'contact' })
 db.model('contact').belongsTo(db.model('user'), { as: 'other' })
 db.model('user').hasOne(db.model('user'), { as: 'contact' })
 db.model('user').hasOne(db.model('user'), { as: 'other' })


这应为联系人表提供两列,分别引用用户表的userIdotherId。您应该可以呼叫someUser.getContact()someUser.getOther()

08-07 15:08