我在节点中使用sequelize orm将对象映射到mysql db。基本上我有两个表产品和类别。一个产品属于一个类别,但一个类别可以有多个产品。在类别表格中,我有一列" parent_id "它引用了自己的id。最多可以有三个级别的层次结构。
主要目标是查找具有属于父类别**的任何类别的产品,例如26.我可以在sql中推断查询,如下所示。
select * from product as p join category as c on p.category_id = c.id join
category as c1 on c1.id = c.parent_id join category as c2
on c2.id = c1.parent_id where c.id = 26 or c1.id = 26 or c2.id = 26
在sequelize中,我尝试通过包含以下
之类的引用来加载{
// upto three levels of category
model : category,
as : 'c',
attributes : [ 'id' ],
include : {
model : category,
as : 'c1',
attributes : [ 'id' ],
include : [ {
model : category,
as : 'c2',
attributes : [ 'id' ]
} ]
}
}
该连接完全有效,但如何适合where子句
c.id = 26或c1.id = 26或c2.id = 26
提前致谢。任何帮助都将非常感激。
答案 0 :(得分:0)
尝试在查询的每个级别添加“where objects”。对象适用于表c的第一个。嵌套在include对象中的第二个对象适用于表c1,依此类推。
{
// upto three levels of category
model : category,
as : 'c',
attributes : [ 'id' ],
where { id : 26 },
include : {
model : category,
as : 'c1',
attributes : [ 'id' ],
where { id : 26 },
include : [ {
model : category,
as : 'c2',
attributes : [ 'id' ],
where { id : 26 }
} ]
}
}