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.
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.
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.
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) {
/* ... */
});
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With