'Creating a one to one association with sequelize nodejs and postgresql
I am currently working a project using NodeJS and postgresql with Sequelize as the ORM.
I have two tables; and address table and a user table. I want the address primary key to be a foreign key in the user table.
THIS is how I have defined the association.
Address.hasOne(User);
User.belongsTo(Address, {
foreignKey:{
type:Sequelize.IMTEGER,
name: "address_id",
allowNull: false,
},
});
This is the definition of my address table using sequelize;
exports default (sequelize, DataTypes) =>{
const Address = sequelize.define("address ",{
address_id:{
type: DataTypes.INTEGER,
autoIncrement:true,
primaryKey: true,
unique:true
},
address_name:{
type: DataTypes.INTEGER,
allowNull: false,
validate:{
notNull:{
msg: "address name required!"
}
}
});
return Address;
}
And this is the user table:
exports default (sequelize, DataTypes) =>{
const User = sequelize.define("user ",{
user_id:{
type: DataTypes.INTEGER,
autoIncrement:true,
primaryKey: true,
unique:true
},
name:{
type: DataTypes.STRING,
allowNull: false,
validate:{
notNull:{
msg: "Name required!"
}
}
});
return User;
}
But when I run the synchronization, all the other columns get created except for the address_id column I expect in the User table.
I need help! Thank everyone in advance
Solution 1:[1]
At least you need to indicate the same value for foreignKey option in both associations:
Address.hasOne(User, { foreignKey: 'address_id' });
User.belongsTo(Address, , { foreignKey: 'address_id' });
And it's better to explicitly define address_id in User model:
address_id:{
type: DataTypes.INTEGER,
notNull: true
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anatoly |
