我想以一种高效和一致的方式填充目录。(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-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
复制相似问题