我属于User和Project模型的许多关联。什么是最简单的方法,给定一个用户ID,查询,以便我们拥有用户拥有的所有项目,以及每个项目的所有用户?我当前的方法非常复杂,涉及两个单独的查询,然后使用Javascript进行解析。我想我错过了一些可以简化整个过程的重要步骤。下面是REST API响应,我希望返回给最终用户。
{
"user_id": "wru09asf",
"projects": [
{
"id": "project_id",
"content": "Final Year Project",
"users": [
{
"id": "user_id",
"role": "Creator"
}
]
}
]
}
目前我在做
// first function, get all projects
User.findById(user_id).then(function(user) {
user.getProjects({
});
});
// second function, get all users of each project returned
for each project returned, do
Project.findById(project_id).then(function(project) {
project.getUsers();
});
// third function
Combine the two responses using Javascript to get the final API response.
Sequelize模特:
//User (all models are underscored named)
sequelize.define('users', {
id: {
type: DataTypes.STRING,
primaryKey: true
},
password: DataTypes.STRING,
salt: DataTypes.STRING,
email: {
type: DataTypes.STRING,
unique: true
}
});
// Project
sequelize.define('projects', {
id: {
type: DataTypes.STRING,
primaryKey: true
},
content: DataTypes.TEXT
});
// UserProject
sequelize.define('user_project', {
role: DataTypes.STRING
});
关系:
User.belongsToMany(Project, {through: UserProject});
Project.belongsToMany(User, {through: UserProject});
答案 0 :(得分:0)
执行join:
User.findAll({
where: {
id: user_id
},
include: [Project]
}).then(function(user) {
});
答案 1 :(得分:0)
user.getProjects()
User.findById(1).then(function(user){
user.getProjects().then(function(projects){
console.log(projects);
},function(err){
console.log(err);
})
},function(err){
console.log(err);
});