Apply for Zend Framework Certification Training

NodeJs





Sequelize supports the standard associations: 

One-To-One, 
One-To-Many 
Many-To-Many.

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

The HasOne association
The BelongsTo association
The HasMany association
The BelongsToMany association
The guide will start explaining how to define these four types of associations, and then will follow

up to explain how to combine those to define the three standard association types

(One-To-One, One-To-Many and Many-To-Many).

The four association types are defined in a very similar way.

Let's say we have two models, A and B.

Telling Sequelize that you want an association between the two needs just a function call:

const A = sequelize.define('A', /* ... */);
const B = sequelize.define('B', /* ... */);

A.hasOne(B); // A HasOne B
A.belongsTo(B); // A BelongsTo B
A.hasMany(B); // A HasMany B
A.belongsToMany(B, { through: 'C' }); // A BelongsToMany B through the junction table C

The A.hasOne(B) association means that a One-To-One relationship exists between A and B, with the foreign key being defined in the target model (B).

The A.belongsTo(B) association means that a One-To-One relationship exists between A and B, with the foreign key being defined in the source model (A).

The A.hasMany(B) association means that a One-To-Many relationship exists between A and B, with the foreign key being defined in the target model (B).

These three calls will cause Sequelize to automatically add foreign keys to the appropriate models (unless they are already present).

The A.belongsToMany(B, { through: 'C' }) association means that a Many-To-Many relationship exists between A and B, using table C as junction table, which will have the foreign keys (aId and bId, for example). Sequelize will automatically create this model C (unless it already exists) and define the appropriate foreign keys on it.

< How to Implement Logging in a Node.js Application How to use cache on node server >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top