【发布时间】:2020-11-10 07:34:42
【问题描述】:
在我的应用程序中,我使用的是 sequelize ORM。有几个实体:Tool 可以有 Tags 和 Categories。
现在我想搜索所有具有特定Tag 的Tools,但我想包括该工具的所有相关Tags(不仅仅是特定的)。如果我现在将where 语句放入包含中,则只有指定的Tags 包含在结果集中(请参阅[2])。我试图在外部 where 语句中限制 Tags(参见 [1]),但这也无济于事。
示例
工具A 具有标签t1、t2 和t3。现在我想搜索所有具有标签t3 的工具,但结果集应包含所有三个标签。
预期结果:
Tool A
\
- Tag t1
- Tag t2
- Tag t3
db.Tool.scope('published').findAll({
where: { '$tool.tag.name$': filter.tag }, // [1] Does not work
include: [
{
model: db.User,
attributes: ['id', 'username']
},
{
model: db.Tag,
attributes: ['name'],
through: { attributes: [] },
// [2] Would limit the result specified tag
// where: {
// name: {
// [Op.and]: filter.tag
// }
// }
},
{
model: db.Category,
attributes: ['id', 'name', 'views'],
through: { attributes: ['relevance'] },
where: {
id: {
[Op.and]: filter.category
}
}
}
],
where: {
title: {
[Op.like]: `%${filter.term}%`,
}
},
attributes: ['id', 'title', 'description', 'slug', 'docLink', 'vendor', 'vendorLink', 'views', 'status', 'createdAt'],
order: [['title', 'ASC'], [db.Tag, 'name', 'ASC']]
})
我知道我可以通过首先通过标签执行选择来执行此操作(db.Tag.findAll() 而不是db.Tool.findAll();I've already done this elsewhere in my project),但同时我也希望能够通过另一个过滤实体 (Category) 以同样的方式。所以Tool.findAll()应该是起点。
任何帮助表示赞赏!
【问题讨论】:
标签: sql node.js sequelize.js where-clause