Sequelizejs - 搜索多对多关系

时间:2014-10-05 07:01:43

标签: sequelize.js

如果用户有多个项目,反之亦然,我可以通过user.getProjects()获取所有用户项目 - 但是有没有办法搜索这个关系,这样你就可以翻阅结果并过滤(比如项目名称) )?

感谢。

https://gist.github.com/be3bafe8903d6b18f4ef.git

// connect
var Sequelize = require("sequelize")
var sequelize = new Sequelize('spike', 'anon', 'password', {
  logging: console.log
});

// models
var User = sequelize.define('User', {
  name: Sequelize.STRING
});

var Project = sequelize.define('Project', {
  name: Sequelize.STRING,
  status: Sequelize.TEXT
});

// associations
Project.hasMany(User, { as: 'User', as: 'contributors' });
User.hasMany(Project, { as: 'contributors' });

// execute
sequelize.sync({force: true}).then(function () {
  User.create({name: 'u1'}).then(function (user1) {
    Project.create({name: 'p1'}).then(function (project1) {
      user1.addContributor(project1).then(function () {
        user1.getContributors().then(function (projects) {
          console.log('User has '+projects.length+ ' projects');
        })
      });
    });
  });
});

1 个答案:

答案 0 :(得分:0)

答案很简单 - 遵循与其他查询相同的模型:

user1.getContributors({where: {name:'p1'}, offset: 1, limit: 2}).then(function (projects) {
    console.log('User has '+projects.length+ ' projects');
})

这产生了以下SQL,它正在分析结果集并过滤PROJECT名称:

SELECT 
    `Project` . *
FROM
    (SELECT 
        `Project`.`id`,
            `Project`.`name`,
            `Project`.`status`,
            `Project`.`createdAt`,
            `Project`.`updatedAt`,
            `ProjectsUser`.`createdAt` AS `ProjectsUser.createdAt`,
            `ProjectsUser`.`updatedAt` AS `ProjectsUser.updatedAt`,
            `ProjectsUser`.`UserId` AS `ProjectsUser.UserId`,
            `ProjectsUser`.`ProjectId` AS `ProjectsUser.ProjectId`
    FROM
        `Projects` AS `Project`
    INNER JOIN `ProjectsUsers` AS `ProjectsUser` ON `Project`.`id` = `ProjectsUser`.`ProjectId`
        AND `ProjectsUser`.`UserId` = 1
    WHERE
        (`Project`.`name` = 'p1')
    LIMIT 1 , 2) AS `Project`;

而且,你可以从另一方面做同样的事情 - 例如查询拥有用户的项目,进行适当的过滤:

p2.getContributors({where: {name: 'u1'}}).then(function(users) {
  console.log('Project 1 has '+users.length+' user named u1');
});