Sequelize ORM
CLI commands and ORM patterns for Sequelize.
Published January 15, 2025 ET
CLI
New migration
sequelize-cli migration:create --name name_of_new_migration
Undo migration
docker-compose run web /usr/local/bin/yarn sequelize-cli db:migrate:undo --name 20200630045621-create-call-notes --url postgres://pbm_user:pbm_password@db/pbm
Seed from a specific seed file
sequelize-cli db:seed --url $POSTGRES_URL --seed name-of-file.js
Seed all seeder files
sequelize-cli db:seed:all --url $POSTGRES_URL
For this, must have a .sequelizerc file:
const path = require('path');
module.exports = {
'config': path.resolve('config', 'config.json'),
'models-path': path.resolve('src/models'),
'seeders-path': path.resolve('seeders'),
'migrations-path': path.resolve('migrations')
}
Eager Loading
This refers to when you query a table by the properties in another table, i.e. a Join query.
https://codewithhugo.com/using-es6-classes-for-sequelize-4-models/
This is fairly straightforward, but you do need to define associations in the sequelize models, and those associations do need to explicitly reference the foreign and target keys being used in the queries:
static associate(models) {
this.hasMany(models.prescription, { foreignKey: "id" });
}
static associate(models) {
this.belongsTo(models.member, { foreignKey: "member_id", targetKey: "id" });
}