【问题标题】:Sequelize: Category Model hierarchical structure with self referenceSequelize:具有自引用的类别模型层次结构
【发布时间】:2018-03-12 15:15:55
【问题描述】:

我的 MySQL 数据库包含一个类别表(也许这里的“父”列是错误的方法):

+----+--------------+--------+
| id |     name     | parent |
+----+--------------+--------+
|  1 | Service      | null   |
|  2 | Lifestyle    | null   |
|  3 | Food & Drink | 2      |
|  4 | Beauty       | 2      |
+----+--------------+--------+

如何使用 Sequelize 以下列形式构造和检索数据:

[
    {
        "id": 1,
        "name": "Service",
        "children": null
    },
    {
        "id": 2,
        "name": "Lifestyle",
        "children": [
                      {
                        "id": 3,
                        "name": "Food & Drink",
                        "children": null
                      },
                      {
                        "id": 4,
                        "name": "Beauty",
                        "children": null
                      },
                    ]
    }
]

我正在使用 Sequelize cli。这是我尝试过的:

查询类别:

    const result = await models.Category.findAll({
        where: {
          parent: null
        },
        include: ['Category']
      });
    res.send(result);

我的类别模型:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Category = sequelize.define(
    'Category',
    {
      name: {
        allowNull: false,
        type: DataTypes.STRING
      },
      parent: { type: DataTypes.INTEGER }
    },
    {}
  );
  Category.associate = function(models) {
    models.Category.belongsTo(models.Category, {
      onDelete: 'CASCADE',
      foreignKey: 'parent'
    });
  };
  return Category;
};

导致以下错误:

“不是唯一的表/别名:'Category'”

什么是构建我的类别的正确解决方案?使用子代而不是父代?

【问题讨论】:

    标签: javascript mysql node.js express sequelize.js


    【解决方案1】:

    尝试在类别模型中添加:

    as: 'children'
    

    改变

    belongsTo
    

    hasMany
    

    喜欢:

    'use strict';
    module.exports = (sequelize, DataTypes) => {
      const Category = sequelize.define(
        'Category',
        {
          name: {
            allowNull: false,
            type: DataTypes.STRING
          },
          parent: { type: DataTypes.INTEGER }
        },
        {}
      );
      Category.associate = function(models) {
        models.Category.hasMany(models.Category, {
          onDelete: 'CASCADE',
          foreignKey: 'parent',
          as: 'children'
        });
      };
      return Category;
    };
    

    您的查询类别现在看起来像:

    const result = await models.Category.findAll({
        where: {
          parent: null
        },
        include: [{
          model: models.Category,
          as: 'children'
        }]
      });
    res.send(result);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多