首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用Sequelize填充树

如何使用Sequelize填充树
EN

Stack Overflow用户
提问于 2015-08-12 06:16:13
回答 3查看 2.9K关注 0票数 1

我想以一种高效和一致的方式填充目录。(ids应始终相同)使用引用自身的模型来创建多树结构:

代码语言:javascript
运行
复制
var Category = sequelize.define("Category", {
  name: DataTypes.STRING
}, {
  timestamps: false,
  classMethods: {
    associate: function(models) {
      Category.hasMany(models.Category, {
        as: 'Children',
        foreignKey: 'ParentId',
        useJunctionTable: false
      });
    }
  }
});

数据示例:

代码语言:javascript
运行
复制
var categories = [
{ name: "Menu A", Children: [
  { name: "Sub 1"},
  { name: "Sub 2", Children: [
    { name: "Element 1" },
    { name: "Element 2" }
  ]},
]}
];

ATM I可以创建所有类别,如下所示:

代码语言:javascript
运行
复制
var process = function (node) {
  node.forEach(function (value, index, array) {
    models.Category.create(value);
    if(value.Children){
      process(value.Children);
    }
  });
  return node;
}

process(categories);

但我错过了模型的联想。

EN

Stack Overflow用户

发布于 2015-08-13 05:06:23

不是完美的解决方案(我不擅长承诺),但这里有一个快速而肮脏的方法:

, Childs: []}添加到所有节点。

并用嵌套的横冲直撞的方式处理它们!

代码语言:javascript
运行
复制
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);
});

丑陋,但工作,仍然在寻找一种好的方式来做这件事。

票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31952920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档