模型定义如下:
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}}选项。
答案 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
}]
});