module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
"User",
{
username: {
type: DataTypes.STRING,
unique: true
},
firstName: {
type: DataTypes.STRING
},
lastName: {
type: DataTypes.STRING
},
email: {
type: DataTypes.STRING
},
password: {
type: DataTypes.STRING
},
lastLogin: {
type: DataTypes.DATE
},
active: {
type: DataTypes.BOOLEAN
},
lastName: {
type: DataTypes.STRING
}
}, {
paranoid: true,
classMethods: {
associate: models => {
User.hasOne(models.User, {
as: "createdByUser"
})
User.hasOne(models.User, {
as: "updatedByUser"
})
}
}
}
)
return User
};
I would expect a field to be called createdByUser
in the Postgres DB, but it's not there. What am I doing wrong?
To create a One-To-Many relationship, the hasMany and belongsTo associations are used together; To create a Many-To-Many relationship, two belongsToMany calls are used together.
Sequelize association methods also accept an options object that you can use to configure the details of the association. For example, you can change the foreign key name on the table by adding the foreignKey property: User. hasOne(Invoice, { foreignKey: "invoice_creator", // UserId -> invoice_creator });
Models can be defined in two equivalent ways in Sequelize: Calling sequelize.define(modelName, attributes, options) Extending Model and calling init(attributes, options)
Solution was
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
"User",
{
username: {
type: DataTypes.STRING,
unique: true
},
firstName: {
type: DataTypes.STRING
},
lastName: {
type: DataTypes.STRING
},
email: {
type: DataTypes.STRING
},
password: {
type: DataTypes.STRING
},
lastLogin: {
type: DataTypes.DATE
},
active: {
type: DataTypes.BOOLEAN
}
}, {
paranoid: true
}
)
User.associate = models => {
User.hasOne(models.User, {
as: "createdByUser"
})
User.hasOne(models.User, {
as: "updatedByUser"
})
}
return User
};
In the new version of Sequelize (4+), there's no need for classMethods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With