我有两个模型:品牌和类别,它们与多对多关系相关联。类别是品牌的选择。
我想创建一个"类别"过滤器,为此,我需要获得所有已过滤类别的品牌,但仍需要将所有类别链接到该品牌。
这就是我所拥有的:
Brand.findAll({
attributes: ['id'],
include: [
{
model: Category,
as: 'categories',
attributes: ['id'],
where: {},
through: {where:{id:1}},
},
],
order : [['name','ASC']],
offset: offset,
limit: limit,
})
这是它生成的MySQL:
SELECT brand.id,
FROM (
SELECT brand.id
FROM brands AS brand
WHERE (
SELECT brandCategory.brandId
FROM brandCategories AS brandCategory
INNER JOIN categories AS category ON brandCategory.categoryId = category.id
WHERE (
brand.id = brandCategory.brandId AND brandCategory.id = 1
) LIMIT 1
) IS NOT NULL
ORDER BY brand.name ASC
LIMIT 0, 20
)
AS brand
INNER JOIN (
brandCategories AS categories.brandCategory
INNER JOIN categories AS categories ON categories.id = categories.brandCategory.categoryId AND categories.brandCategory.id = 1
) ON brand.id = categories.brandCategory.brandId
include的where对象使它成为必需,因此我有检查Category存在的请求。但由于它最终也在INNER JOIN中,它并不能获得所有类别,只有过滤后的类别。
如果我直接在include中使用where : {id : 1}
而不是"通过",我不会让所有链接的模型+分页不起作用,如LIMIT在请求中,仅检查关系是否存在(但未链接到已过滤的ID)。
我是否应该忘记include中的where和through参数,并在findAll的根目录中使用文字表达式来替换检查关系存在的函数?