[英]Multiple foreignkey in Sequelize + Nodejs
我有一個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' })
這應該為聯系表提供兩列, userId
和otherId
都引用用戶表。 您應該能夠調用someUser.getContact()
和someUser.getOther()
您可能要嘗試執行的操作可能如下所示:
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
}
});
Users.associate = (models) => {
Users.belongsTo(models.RefreshToken, {
foreignKey: 'userId'
});
Users.belongsTo(models.RefreshToken, {
foreignKey: 'email'
});
};
return Users;
}
我注意到您正在使用sequelize v3樣式,請嘗試閱讀sequelize文檔,了解當前如何支持如何遷移到v4。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.