1. 程式人生 > >Sequelize-nodejs-13-Working with legacy tables

Sequelize-nodejs-13-Working with legacy tables

Working with legacy tables使用遺留表

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

雖然開箱即用的Sequelize會顯得有點固執己見,但是可以通過定義(否則生成)表和欄位名來使用你的應用的遺留和之前的憑據,這是微不足道的。

 

Tables表

sequelize.define('user', {

}, {
  tableName: 'users'
});

 

Fields欄位

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

 

Primary keys主鍵

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

Sequelize將假設您的表預設具有id主鍵屬性

To define your own primary key:

想要定義你自己的主鍵:

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

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

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

 

Foreign keys外來鍵

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