递归包括Sequelize? [英] Recursive include Sequelize?
问题描述
我有可以拥有子类别的类别
I have category that can have child categories
当我在做findAll我想要包括所有那些嵌套,但我不知道深度。
And when I'm doing findAll I want to include all of those nested, but I don't know the depth.
var includeCondition = {
include: [
{
model: models.categories,
as:'subcategory', nested: true
}]
};
models.categories.findAll(includeCondition)
.then(function (categories) {
resolve(categories);
})
.catch(function (err) {
reject(err);
})
});
结果只给我一个级别的嵌套包含。
The result brings me only one level nested include.
[
{
dataValues:{
},
subcategory:{
model:{
dataValues:{
}
// no subcategory here
}
}
}
]
我可以以某种方式使sequalize包括那些嵌套的子类别吗?
Can I somehow make sequalize include those nested subcategories ?
推荐答案
如果找到这个
的解决方案很少,第一个更复杂但会提供更好的性能:
There are few solutions if found for this first one is more complicated but will give better performance:
这个是关于在MySQL中实现分层数据结构
我喜欢这里的指南
This one is about implementing hierarchical data structure in MySQL I like the guide here
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
名为The Nested Set Mod的那个el。
The one that is named The Nested Set Model.
我自己实际实现的第二个解决方案是递归扩展,这个使用了很多mysql请求,我相信可以改进,但它是一个快速的,效果很好。事情是用于这样的每个类别函数
The second solution that I actually implemented by myself is recursive expanding, this one uses lots of mysql requests and I believe can be improved, but it's a fast one and works well. The thing is to use for each category function like this
var expandSubcategories = function (category) {
return new promise(function (resolve, reject) {
category.getSubcategories().then(function (subcategories) {
//if has subcategories expand recursively inner subcategories
if (subcategories && subcategories.length > 0) {
var expandPromises = [];
_.each(subcategories, function (subcategory) {
expandPromises.push(expandSubcategories(subcategory));
});
promise.all(expandPromises).then(function (expandedCategories) {
category.subcategories = [];
_.each(expandedCategories, function (expandedCategory) {
category.subcategories.push(expandedCategory);
}, this);
//return self with expanded inner
resolve(category);
});
} else {
//if has no subcategories return self
resolve(category);
}
});
});
};
所以它会通过类别并递归扩展它们。
So it's going through the categories and expanding them recursively.
也许这对某人也有帮助。
Maybe this will help someone as well.
这篇关于递归包括Sequelize?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!