Sequelize 中文文檔 v4 - Working with legacy tables - 使用遺留表

Working with legacy tables - 使用遺留表

此係列文章的應用示例已發佈於 GitHub: sequelize-docs-Zh-CN. 能夠 Fork 幫助改進或 Star 關注更新. 歡迎 Star.git

雖然 Sequelize 自認爲能夠開箱即用, 可是若是你要使用應用以前遺留的資產和憑據,僅須要作一點微不足道的設置便可。github

sequelize.define('user', {

}, {
  tableName: 'users'
});

字段

sequelize.define('modelName', {
  userId: {
    type: Sequelize.INTEGER,
    field: 'user_id'
  }
});

主鍵

Sequelize將假設您的表默認具備id主鍵屬性。ide

要定義你本身的主鍵:post

sequelize.define('collection', {
  uid: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true // Automatically gets converted to SERIAL for postgres
  }
});

sequelize.define('collection', {
  uuid: {
    type: Sequelize.UUID,
    primaryKey: true
  }
});

若是你的模型根本沒有主鍵,你能夠使用 Model.removeAttribute('id');ui

外鍵

// 1:1
Organization.belongsTo(User, {foreignKey: 'owner_id'});
User.hasOne(Organization, {foreignKey: 'owner_id'});

// 1:M
Project.hasMany(Task, {foreignKey: 'tasks_pk'});
Task.belongsTo(Project, {foreignKey: 'tasks_pk'});

// N:M
User.hasMany(Role, {through: 'user_has_roles', foreignKey: 'user_role_user_id'});
Role.hasMany(User, {through: 'user_has_roles', foreignKey: 'roles_identifier'});

若是這篇文章對您有幫助, 感謝 下方點贊 或 Star GitHub: sequelize-docs-Zh-CN 支持, 謝謝.code

相關文章
相關標籤/搜索