Working with Legacy Tables

While out of the box Sequelize will seem a bit opinionated it’s easy to work legacy tables and forward proof your application by defining (otherwise generated) table and field names.

Tables

  1. class User extends Model {}
  2. User.init({
  3. // ...
  4. }, {
  5. modelName: 'user',
  6. tableName: 'users',
  7. sequelize,
  8. });

Fields

  1. class MyModel extends Model {}
  2. MyModel.init({
  3. userId: {
  4. type: DataTypes.INTEGER,
  5. field: 'user_id'
  6. }
  7. }, { sequelize });

Primary keys

Sequelize will assume your table has a id primary key property by default.

To define your own primary key:

  1. class Collection extends Model {}
  2. Collection.init({
  3. uid: {
  4. type: DataTypes.INTEGER,
  5. primaryKey: true,
  6. autoIncrement: true // Automatically gets converted to SERIAL for postgres
  7. }
  8. }, { sequelize });
  9. class Collection extends Model {}
  10. Collection.init({
  11. uuid: {
  12. type: DataTypes.UUID,
  13. primaryKey: true
  14. }
  15. }, { sequelize });

And if your model has no primary key at all you can use Model.removeAttribute('id');

Foreign keys

  1. // 1:1
  2. Organization.belongsTo(User, { foreignKey: 'owner_id' });
  3. User.hasOne(Organization, { foreignKey: 'owner_id' });
  4. // 1:M
  5. Project.hasMany(Task, { foreignKey: 'tasks_pk' });
  6. Task.belongsTo(Project, { foreignKey: 'tasks_pk' });
  7. // N:M
  8. User.belongsToMany(Role, { through: 'user_has_roles', foreignKey: 'user_role_user_id' });
  9. Role.belongsToMany(User, { through: 'user_has_roles', foreignKey: 'roles_identifier' });