多對多關係是使用belongsToMany()方法在雙方的重複中定義的。對於您的特定用例,您將不得不爲關係使用直通模型,並直接查詢直通模型。
var User = sequelize.define("user")
var Project = sequelize.define("project")
var ProjectUser = sequelize.define("projectUser")
Project.belongsToMany(User, {
through: ProjectUser
})
User.belongsToMany(Project, {
through ProjectUser
});
ProjectUser.findAll({
where: {
UserId: 'someId'
},
// We only want the project, not the user.
// You might need to do ProjectUser.belongsTo() for both
// models for this to work.
include: [Project]
})
.then(function(results) {
// Here we are getting an array of ProjectUsers, to return all the projects
// we map it to a new array of only projects.
return results.map(function(userProject) {
return userProject.Project;
});
})
這是一個多對多的關係嗎? – grimurd
是的,這是一個多對多的關係 –