[英]Association sequelize 3 tables, many to many
I have 4 tables 我有4张桌子
- client
- project
- user
- userProject
One Project belongs to client and it needs to have client foreign key client_id. 一个项目属于客户端,它需要客户端外键client_id。
UserProject has project_id and user_id foreign keys, belongs to project and user. UserProject具有project_id和user_id外键,属于项目和用户。
One user owns the clients of his projects. 一个用户拥有他的项目的客户。
I'm wondering you could use eager loading feature from sequalize : 我想知道你可以使用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
. 这在user
和project
之间创建了多对多关系。 Between user
and client
you therefor have a many-to-many-to-one relation. 在user
和client
之间,你有一个多对多的关系。 This is not supported by sequelize. sequelize不支持此功能。 I would have created an instance method on the User
model like this: 我会在User
模型上创建一个实例方法,如下所示:
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.