使用Sequelize,如何在不包含连接模型的属性的情况下查询模型?

时间:2015-03-13 21:53:12

标签: sequelize.js

模型定义如下:

Team = sequelize.define 'team',
  name: Sequelize.STRING

User = sequelize.define 'user',
  name: Sequelize.STRING
  foo: Sequelize.INTEGER

Team.hasMany User
User.belongsTo Team

如何让所有团队都包含foo等于42的用户,而不在结果中包含用户,并且在结果中没有多次相同的团队,即如何生成以下查询?

SELECT DISTINCT team.id, team.name
FROM team
INNER JOIN user ON user.team_id = team.id
WHERE user.foo = 42

修改:查询应为a raw query,即使用raw的{​​{1}}选项。

1 个答案:

答案 0 :(得分:0)

要使内部联接在include方法的find*选项中使用required = true。怎么样DISTINCT - 你可以试试这个黑客:

Team.findAll({ 
    attributes: ['DISTINCT team.id','team.name'], // hack with distinct
    include: [{ 
        model: User, 
        required: true, // inner join
        attributes: []  // exclude user fields from select
    }] 
});