Working with legacy tables - 使用遗留表

虽然 Sequelize 自认为可以开箱即用, 但是如果你要使用应用之前遗留的资产和凭据,仅需要做一点微不足道的设置即可。

  1. sequelize.define('user', {
  2. }, {
  3. tableName: 'users'
  4. });

字段

  1. sequelize.define('modelName', {
  2. userId: {
  3. type: Sequelize.INTEGER,
  4. field: 'user_id'
  5. }
  6. });

主键

Sequelize将假设您的表默认具有id主键属性。

要定义你自己的主键:

  1. sequelize.define('collection', {
  2. uid: {
  3. type: Sequelize.INTEGER,
  4. primaryKey: true,
  5. autoIncrement: true // Automatically gets converted to SERIAL for postgres
  6. }
  7. });
  8. sequelize.define('collection', {
  9. uuid: {
  10. type: Sequelize.UUID,
  11. primaryKey: true
  12. }
  13. });

如果你的模型根本没有主键,你可以使用 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.hasMany(Role, {through: 'user_has_roles', foreignKey: 'user_role_user_id'});
  9. Role.hasMany(User, {through: 'user_has_roles', foreignKey: 'roles_identifier'});