如何使用Sequelize填充树
我想以一种有效和一致的方式填充一个目录。 (ID应始终相同)使用引用自己的模型来构build多树结构:
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我可以创build所有类别,如:
var process = function (node) { node.forEach(function (value, index, array) { models.Category.create(value); if(value.Children){ process(value.Children); } }); return node; } process(categories);
但我错过了模型协会。
我使用模块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 } } ]
希望这可以帮助
不是完美的解决scheme,(我不擅长承诺),但这是一个快速和肮脏的方式:
向所有节点添加, 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); });
丑陋的,但做这个工作,仍然在寻找一个漂亮的方式来做到这一点。