Sequelize Association References

Daily Standup

Sequelize Association References

I ran into a weird occurrence where I had created a model in which one field was a reference to another model:

const Notebook = sequelize.define('Notebook', {...,
shelf_id: {
type: Sequelize.INTEGER,
unique: true,
validate: {
notEmpty: true,
},
references: {
model: 'Shelves',
key: 'shelf_id',
},
},
});

I also associated the two models:

Notebook.associate = models => {
Notebook.belongsTo(models.Shelf);
};

However when looking at the SQL table definition to check everything was set up correctly, the shelf_id column was defined, but did not include an actual reference to another table.

First I tried removing the shelf_id column definition from my model, and this solved the problem—the column was added automatically due to the belongsTo association. However I’d lost my validations, and the column had a terrible name shelf_shelf_id. Another nitpicky point—it added the shelf_shelf_id column after the created_at and updated_at columns, when I prefer those to be at the absolute end, looking at the table left to right.

To solve the column name problem it was an easy adjustment:

Notebook.associate = models => {
Notebook.belongsTo(models.Shelf, { foreignKey: 'shelf_id' });
};

However it was still added to the end, and the reference still wasn’t being picked up.

Next I tried adding the shelf_id column back, and adjusting the association further instead. This worked:

Notebook.associate = models => {
Notebook.belongsTo(models.Shelf, {
foreignKey: 'shelf_id',
sourceKey: 'shelf_id'
});
};

Just adding the foreignKey is not enough; to trigger the reference, sourceKey must be defined as well.

Up Next

I made progress on another piece of app but a question came up: can I add an association between two models and use each to call the other without adding a reference to both? Will research that next and then finish out what I’m working on.