I have a user table that has a foreign key column to a roles table.
I defined all relationships in mysql and using sequelize-auto I generated my models.
The generated model for user was this:
const user = sequelize.define('user', {
Id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
Email: {
type: DataTypes.STRING(45),
allowNull: false,
unique: true,
},
RoleId: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'roles',
key: 'Id',
},
},
});
I thought that my reference was set so that when I did the following in my resolver:
users: async () => {
const users = await db.user.findAll({
include: [
{
model: db.roles,
},
],
});
return users
I should have gotten back a list of user roles with the following query in the playground:
{users
{roles
{Name, Id}
}
}
instead I got
roles is not associated to user!
What I later figured out is that I needed to make an association:
user.associate = models => {
user.hasMany(models.roles, {
foreignKey: 'Id',
sourceKey: 'RoleId',
onDelete: 'cascade',
});
};
Then it worked.
What I still dont understand is what is this for in the user-model?:
references: {
model: 'roles',
key: 'Id',
},
I thought that it was my "association" with the roles table but without me explicitly adding an association this simply did nothing. Can someone please explain the meaning of references field?
references is for describing a model in a migration and for auto-creating tables using the sync function. To manipulate data (not a structure) you use associations like user.hasMany