Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Association sequelize 3 tables, many to many

I have 4 tables

- client
- project
- user
- userProject

One Project belongs to client and it needs to have client foreign key client_id.

UserProject has project_id and user_id foreign keys, belongs to project and user.

One user owns the clients of his projects.

  • How can I list the clients of one user?
like image 215
David Avatar asked Mar 11 '14 20:03

David


People also ask

How do you do associations in Sequelize?

Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target). hasOne - adds a foreign key to the target and singular association mixins to the source.

What does many belongs to many Sequelize?

The Sequelize belongsToMany() method is used to create a Many-To-Many association between two tables. Two tables that have a Many-To-Many relationship require a third table that acts as the junction or join table. Each record in the junction table will keep track of the primary keys of both models.


2 Answers

I'm wondering you could use eager loading feature from sequalize:

Client.findAll({
  include: [{
    model: Project,
    include: [{
      model: User,
      where: {
        id: <UserId>
      },
      required: false
    }]
  }]
}).then(function(clients) {
  /* ... */
});
like image 160
oleh.meleshko Avatar answered Nov 08 '22 20:11

oleh.meleshko


This creates a many-to-many relation between user and project. Between user and client you therefor have a many-to-many-to-one relation. This is not supported by sequelize. I would have created an instance method on the User model like this:

User = sequelize.define('user', {
  // ... definition of user ...
},{
  instanceMethods: {
    getClients: function()  { 
      return this.getProjects().then(function (projects) {
        var id_map = {};
        for (var i = 0; i < projects.length; i++) {
          id_map[projects[i].clientId] = 1;
        }
        return Client.findAll({
          where: { id: [Object.keys(id_map)] }
        });
      });
    }
  }
});

and then call this function when you have a user instance like this, to get the clients:

user.getClients().then(function (clients) {
  console.log(clients);
});
like image 30
bolav Avatar answered Nov 08 '22 19:11

bolav