Hi @anon79585656
When trying to change the user_id
field referenced in my address model, I 'm getting new errors, and it is not normal.
If I set
db.addresses.belongsTo(db.users, { as: 'user', foreignKey: 'user.id' })
I’m getting
SequelizeDatabaseError: column addresses.user.id does not exist
If I set
db.addresses.belongsTo(db.users, { as: 'user', foreignKey: 'id' })
I’m getting no error (because the id field in addresses exist), but there is no more link from addresses
to users
.
My relation is correct: foreign_key
should define the source key in addresses
: it is user_id.
Here is an excerpt of my users
table:
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('users',
{
id: {
type: DataTypes.UUIDV4,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true,
},
created_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false,
},
updated_at: {
type: DataTypes.DATE,
allowNull: true,
},
deleted_at: {
type: DataTypes.DATE,
allowNull: true,
},
email: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isEmail: {
args: true,
msg: 'Please enter a valid email address.',
},
len: [10, 50],
},
},
...
status: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 1,
},
}, {
tableName: 'vusers',
timestamps: false,
underscored: true,
schema: process.env.DATABASE_SCHEMA,
});
And an excerpt of my addresses
table:
module.exports = (sequelize, DataTypes) => {
const Address = sequelize.define('addresses',
{
id: {
type: DataTypes.UUIDV4,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true,
},
created_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false,
},
updated_at: {
type: DataTypes.DATE,
allowNull: true,
},
deleted_at: {
type: DataTypes.DATE,
allowNull: true,
},
street: {
type: DataTypes.STRING,
allowNull: false,
},
....
user_id: {
type: DataTypes.UUIDV4,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
}, {
tableName: 'addresses',
timestamps: false,
underscored: true,
});