Sequelize:类别模型层次结构与自我引用

时间:2018-03-12 15:15:56

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

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

sessionFactory

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

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

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

查询类别:

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

我的分类模型:

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

导致以下错误:

  

"不是唯一的表/别名:'类别'"

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

1 个答案:

答案 0 :(得分:2)

尝试添加类别模型:

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);