如何在sequelizejs中通过外键查找数据?

时间:2016-04-24 11:58:10

标签: node.js sequelize.js

我定义了这些数据(多对多关系):

    exports.User = sequelize.define('user', {
        name: {
            type: Sequelize.STRING,
            unique: true,
        },
        email: {
            type: Sequelize.STRING,
            unique: true
        },
        password: {
            type: Sequelize.STRING
        }
    });


    exports.Project = sequelize.define('project', {
        name: {
            type: Sequelize.STRING,
            unique: true
        },
        description: {
            type: Sequelize.STRING
        }
    });

    exports.User.belongsToMany(exports.Project, {as: 'Projects', through: 'user_projects', foreignKey: 'userId'});
    exports.Project.belongsToMany(exports.User, {as: 'Users', through: 'user_projects', foreignKey: 'projectId'});

如果我知道用户ID,如何查询此用户中的所有项目。 我现在做什么:

db.User.findById(userId).then(function (user) {
      user.getProjects().then(function(projects){
            //get
      });
 });

我可以按ID获取项目,而不是两次查询吗?

1 个答案:

答案 0 :(得分:0)

我想你可以做到:

var query = {
  where: {id: userId},
  include: [
    {model: db.Project, as: 'Projects'}
  ]
}

db.User.findOne(query).
  then(function (user) {
    var projects = user.Projects
    ...
  });