我想以一种高效和一致的方式填充目录。(ids应始终相同)使用引用自身的模型来创建多树结构:
var Category = sequelize.define("Category", {
name: DataTypes.STRING
}, {
timestamps: false,
classMethods: {
associate: function(models) {
Category.hasMany(models.Category, {
as: 'Children',
foreignKey: 'ParentId',
useJunctionTable: false
});
}
}
});数据示例:
var categories = [
{ name: "Menu A", Children: [
{ name: "Sub 1"},
{ name: "Sub 2", Children: [
{ name: "Element 1" },
{ name: "Element 2" }
]},
]}
];ATM I可以创建所有类别,如下所示:
var process = function (node) {
node.forEach(function (value, index, array) {
models.Category.create(value);
if(value.Children){
process(value.Children);
}
});
return node;
}
process(categories);但我错过了模型的联想。
发布于 2015-08-12 23:13:26
我使用模块https://github.com/domasx2/sequelize-fixtures来实现与您类似的功能。
使用此模块,您可以使用固定ID和关联将数据加载到数据库中:
[
{
"model": "Owner",
"data": {
"id": 11,
"name": "John Doe",
"city": "Vilnius"
}
},
{
"model": "Car",
"data": {
"id": 203,
"make": "Ford",
"owner": 11
}
}
]希望这能有所帮助
发布于 2019-06-14 17:58:33
2年后的2021年更新-截至2021年10月13日,sequelize-hierarchy存在内存泄漏,过去两年没有更新
有另一个名为sequelize-hierarchy的Node包可以实现这一点,并且根据它的描述;
“关系数据库不太擅长处理嵌套的层次结构……
要在数据库中存储层次结构,通常的方法是为每条记录提供一个ParentID字段,该字段指示哪个记录是其上一级的记录。
获取任何记录的父项或子项都很容易,但如果要从数据库中检索整个树/层次结构,则需要多次查询,递归地获取层次结构的每一层。对于大树结构,这是一个冗长的过程,而且代码也很烦人。
Sequelize的这个插件解决了这个问题。
你可以在here上找到它
发布于 2015-08-13 05:06:23
不是完美的解决方案(我不擅长承诺),但这里有一个快速而肮脏的方法:
将, Childs: []}添加到所有节点。
并用嵌套的横冲直撞的方式处理它们!
function processNode(node) {
models.Category.create(node).then(function(created){
node.Childs.forEach(function(child){
models.Category.create(child).then(function(theChild) {
created.addChild(theChild);
child.Childs.forEach(function(grandChild){
models.Category.create(grandChild).then(function(theGrandChild){
theChild.addChild(theGrandChild);
grandChild.Childs.forEach(function(grandGrandChild){
models.Category.create(grandGrandChild).then(function(theGrandGrandChild){
theGrandChild.addChild(theGrandGrandChild);
})
})
})
})
})
})
});
}
categories.forEach(function(mainCategory){
processNode(mainCategory);
});丑陋,但工作,仍然在寻找一种好的方式来做这件事。
https://stackoverflow.com/questions/31952920
复制相似问题