Working with legacy tables - 使用遗留表

虽然 Sequelize 自认为可以开箱即用, 但是如果你要使用应用之前遗留的资产和凭据,仅需要通过定义(否则生成)表和字段名称即可.

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

字段

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

主键

Sequelize将假设你的表默认具有id主键属性.

要定义你自己的主键:

  1. class Collection extends Model {}
  2. Collection.init({
  3. uid: {
  4. type: Sequelize.INTEGER,
  5. primaryKey: true,
  6. autoIncrement: true // 对于 postgres 自动转换为 SERIAL
  7. }
  8. }, { sequelize });
  9. class Collection extends Model {}
  10. Collection.init({
  11. uuid: {
  12. type: Sequelize.UUID,
  13. primaryKey: true
  14. }
  15. }, { sequelize });

如果你的模型根本没有主键,你可以使用 Model.removeAttribute('id');

外键

  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' });