简体   繁体   中英

how to make relationship between 2 tables using Node.js Express.js and Sequelize ORM

Hi guys I'm in process of developing a web application using angular and node.js in the backend part, I used express.js and Sequelize ORM to make the server and the database but while I'm creating the tables I got some problem which is how to how to make a relationship between 2 tables Can you help me guys.! and thanks a lot.

Sequelize supports the standard associations betwen tables: One-To-One, One-To-Many and Many-To-Many.

To do this, Sequelize provides four types of associations that should be combined to create them:

  • HasOne association
  • BelongsTo association
  • HasMany association
  • BelongsToMany association

If you want more in detail info watchout sequelize docu: https://sequelize.org/master/manual/assocs.html

For a one-one relationships you define the two tables and then define the relationship

db.Table2.Table1 = db.Table2.belongsTo(db.Table1, {
    foreignKey: {
        name: “sharedId"
    }
});
db.Table1.Table2 = db.Table1.hasOne(db.Table2, {
    foreignKey: {
        name: "sharedId"
    }
});

For one-many relationships, you would change hasOne to hasMany or belongsTo to belongsToMany.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM