javascript - Sequelize – where with count
问题描述
我有三个模型可以扩展Sequelize.Model
并生成迁移。关联如下所示:
富
Foo.belongsToMany(Bar, {
as: 'bars',
through: 'FooBar',
foreignKey: 'foo_id',
});
酒吧
Bar.belongsToMany(Foo, {
as: 'bars',
through: 'FooBar',
foreignKey: 'bar_id',
});
富吧
FooBar.belongsTo(Foo, {
as: 'foo',
foreignKey: 'foo_id',
});
FooBar.belongsTo(Bar, {
as: 'bar',
foreignKey: 'bar_id',
});
我正在尝试像这样查询 Foo:
const foos = await Foo.findAll({
include: [{
model: Bar,
as: 'bars',
}],
});
代码按预期工作,我得到了bars
每个foo
.
我现在如何查询仅bars
计数大于 2 的 foos?
解决方案
在 sequelize 中没有直接的方法可以做到这一点。
有两种方法可以做到:
- 第一种方式:(2个查询)
- 在 1 个查询中查找所有具有 2 个条的 foo id(可能是原始查询)
- 将这些 foo id 作为过滤器添加到 findAll 的位置
- 第二种方式:(1个查询)
- 创建一个子查询的 sequelize 文字,该文字返回具有 2 个以上 bar 的 foo id,并将该文字添加到
where: { id: <subquery literal> }
- 创建一个子查询的 sequelize 文字,该文字返回具有 2 个以上 bar 的 foo id,并将该文字添加到
显示第二种方式:
子查询文字例如:
sequelize.literal(`(
SELECT
id
FROM foo
LEFT JOIN bar ON bar.foo_id = foo.id
WHERE COUNT(bar.id) > 2
GROUP BY foo.id
)`)
最终findAll:
const foos = await Foo.findAll({
where: {
id: sequelize.literal(`...`),
},
include: [{
model: Bar,
as: 'bars',
}],
});