通过未创建的外键 Sequelize join table

Sequelize join table through foreign keys not created

我正在尝试在 sequelize 中创建用户 > 好友关系。因此,我通过名为 friends 的 join-table 创建了一个用户模型和一个 belongsToMany 关系。它创建了 table 但没有创建 foreignKeys userId 和 friendId。如果有人能帮助我,我会很高兴。

用户模型:

var User = sequelize.define('user', {
    id: {
      type: Sequelize.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    emailaddress: {
      type: Sequelize.STRING
    },
    firstname: {
      type: Sequelize.STRING
    },
    lastname: {
      type: Sequelize.STRING
    },
    description: {
      type: Sequelize.STRING
    },
    password: {
      type: Sequelize.STRING
    }
  }, {
    freezeTableName: true, 
    classMethods: {
      associate: function (models) {
        User.belongsToMany(models.user, {
          as: "user",
          through: "friend"
        });
        User.belongsToMany(models.user, {
          as: "friend",
          through: "friend"
        });
        User.sync({
            force: true
          })
      }
    }
  });

好友模型

var Friend = sequelize.define('friend', {
    // userId: DataTypes.INTEGER,
    // friendId: DataTypes.INTEGER,
    status: {
      type: DataTypes.BOOLEAN,
      defaultValue: 0
    }
  }, {
    freezeTableName: true,
    classMethods: {
      associate: function (models) {
        Friend.sync()
      }
    }
  });

这会在朋友 table 中生成以下字段:

id status createdAt updatedAt

我想要以下字段:

id status userId friendId createdAt updatedAt

package.json > "sequelize": "^3.17.1",

您可以将 otherKeyforeignKey 设置为续集关联。我认为你应该试试这个:

User.belongsToMany(models.user, {
    as: "friends",
    through: "friend",
    otherKey: 'userId',
    foreignKey: 'friendId'
});

抱歉,我现在不能尝试,但希望对您有所帮助。

经过一些调试后,我发现问题是我在初始化每个 table 时调用了 Table.sync,而不是在定义所有 table 时只调用一次(参见github 上的 sequelize express 示例中的示例代码:https://github.com/sequelize/express-example)。这破坏了 table 创建过程。