如何在sequelize js ORM中获得关系/关联

时间:2014-08-29 06:40:40

标签: mysql node.js orm sequelize.js

通过以下参考,我理解如何使用关系表来映射多对多

http://sequelizejs.com/docs/latest/associations#many-to-many

User = sequelize.define('User', { user_name : Sequelize.STRING})
Project = sequelize.define('Project', { project_name : Sequelize.STRING })
UserProjects = sequelize.define('UserProjects', {
    status: DataTypes.STRING
})

User.hasMany(Project, { through: UserProjects })
Project.hasMany(User, { through: UserProjects })

但如何查询用户项目

我试过

User.find({where:{id:1},include,[UserProjects]})
User.find({where:{id:1},include,[Projects]})
User.find({where:{id:1},include,[UserProjects]})
User.find({where:{id:1},include,[Projects]})

但我没有得到结果

Sequelize创建了如下表

users(id,name)
projects(id,project_name)
userprojects(id,UserId,ProjectId)

我尝试了https://github.com/sequelize/sequelize/wiki/API-Reference-Associations#hasmanytarget-options

User.find({where:{id:1}}).success(function(user){
    user.getProjects().success(function (projects) {
      var p1 = projects[0] // this works fine but 2 queries required. I expect in single find. without getProjects
      p1.userprojects.started // Is this project started yet?
    })
})

如何获取USER的所有项目?

1 个答案:

答案 0 :(得分:0)

您应该能够以两种不同的方式获取用户的所有属性:使用包含和从用户实例获取项目。

使用包含您上面提交的代码几乎是正确的。此方法仅使用JOIN操作对数据库进行一次查询。如果您希望所有用户都拥有相应的项目,请尝试:

User.findAll({include: [Project]})

您还可以直接从用户实例获取项目。这将对数据库进行两次查询。这个代码看起来像

User.find(1).then(function(user) {
  user.getProjects().then(function(projects) {
    // do stuff with projects
  });
});

这对你有用吗?