未将所有嵌套行插入表中

时间:2019-02-05 08:54:07

标签: node.js sequelize.js

我想要类别表中的树结构。

所以我尝试了这个:

类别模型如下:

import * as Sequelize from 'sequelize';

export default class CategoriesModel extends Sequelize.Model {
    static init(sequelize, DataTypes) {
        return super.init({
            name: {
                type: DataTypes.STRING,
            },
        }, {
            modelName: 'categories',
            sequelize,
        });
    }
}
我的CategoriesModel类中的

关联如下:


    static associate({ Categories }) {
        this.nestedCategories = this.hasMany(Categories, {
            as: 'nestedCategories',
            foreignKey: 'parentId',
        });
    }

,当我尝试插入行时,例如:

sequelize.sync({ force: true }).then(() => {
    models.Categories.create({
        name: 'parent',
        nestedCategories: [
            {
                name: 'child 1',
            }, 
            {
                name: 'child 2',
                nestedCategories: [
                    {
                        name: 'child 3',
                    }
                ],
            },
        ],
    }, {
        include: [models.Categories.nestedCategories]
    }).then(cat => {
        console.log(cat.toJSON());
    })
});

结果是:

{ 
  id: 1,
  name: 'parent',
  nestedCategories:
   [ { id: 2,
       name: 'child 1',
       parentId: 1,
       updatedAt: 2019-02-05T08:39:45.655Z,
       createdAt: 2019-02-05T08:39:45.655Z },
     { id: 3,
       name: 'child 2',
       parentId: 1,
       updatedAt: 2019-02-05T08:39:45.657Z,
       createdAt: 2019-02-05T08:39:45.657Z } ],
  updatedAt: 2019-02-05T08:39:45.624Z,
  createdAt: 2019-02-05T08:39:45.624Z,
  parentId: null 
}

子3 未插入表中。

我不明白我在做什么错...

1 个答案:

答案 0 :(得分:1)

您需要为每个嵌套类别指定一个include,以便正确解析您的请求。

我在此处创建了一个函数,用于根据要创建的模型递归执行此操作:

console.log(router.history)

在这种情况下,您要包含的内容如下:

function buildIncludeRecursive(model, includeTemplate) {
    const include = Object.assign({}, includeTemplate);
    let currInclude = include;
    let currModel = model;
    while(currModel[includeTemplate.as]){
        currInclude.include = [Object.assign({}, includeTemplate)];
        currInclude = currInclude.includes[0];
        currModel = currModel[includeTemplate.as];
    }
    return include;
}

const model = {
     name: 'parent',
     nestedCategories: [
         { name: 'child 1' }, 
         {
             name: 'child 2',
             nestedCategories: [
                { name: 'child 3' }
             ]
        },
    ],
};

const includeTemplate = {
    model: models.Categories,
    as: 'nestedCategories'
};

model.categories.create(model, { 
    include: buildIncludeRecursive(model, includeTemplate)
});