如何使用从 Sequelize 生成的模型获取关联数据?

How to fetch associated data with models generated form Sequalize?

我一直在开发一个 NodeJs 后端应用程序,该应用程序具有 MySQL 支持,将 Sequelize 作为 ORM。我正在尝试通过调用我创建的 API 来获取数据。它发送数据作为响应。但它不包含与外键关系相关的关联对象。

我已经有一个 MySQL 数据库并且我正在使用 sequelize ORM,我使用 sequelize-auto 生成模型 classes。所有模型 classes 均已成功生成。但是这些关联并不是与模型一起产生的。因此,为了迎合关联,我不得不手动将关联添加到模型 class。然后我创建路由文件并创建 HTTP GET 方法。但是 API 端点没有按预期发送数据。

以下显示了我创建的模型 classes 和路径文件。

module.exports = function(sequelize, DataTypes) {
    const Department = sequelize.define('Department', {
        department_id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: DataTypes.STRING(100),
            allowNull: false
        },
        description: {
            type: DataTypes.STRING(1000),
            allowNull: true
        }
    }, {
        tableName: 'department',
        timestamps: false,
        underscored: true
    });
    Department.associate = function(models) {
        // associations can be defined here
        Department.hasMany(models.Category, {
            foreignKey: 'department_id',
            as: 'categories',
        });
    };
    return Department;
};
module.exports = function(sequelize, DataTypes) {
    const Category = sequelize.define('Category', {
        category_id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        department_id: {
            type: DataTypes.INTEGER(11),
            allowNull: false
        },
        name: {
            type: DataTypes.STRING(100),
            allowNull: false
        },
        description: {
            type: DataTypes.STRING(1000),
            allowNull: true
        }
    }, {
        tableName: 'category',
        timestamps: false,
        underscored: true
    });
    Category.associate = function(models) {
        // associations can be defined here
        Category.belongsTo(models.Department)
    };
    return Category;
};
var express = require('express');
var router = express.Router();
var model = require('../models/index');

/* GET departments listing. */
router.get('/', function(req, res, next) {
    model.Department.findAll({})
        .then(department => res.json({
            error: false,
            data: department
        }))
        .catch(error => res.json({
            data: [],
            error: true
        }));
});
module.exports = router;
var express = require('express');
var router = express.Router();
var model = require('../models/index');

/* GET category listing. */
router.get('/', function(req, res, next) {
    model.Category.findAll({})
        .then(category => res.json({
            error: false,
            data: category
        }))
        .catch(error => res.json({
            data: [],
            error: true
        }));
});
module.exports = router;

响应/部门路线

{
    "error": false,
    "data": [
        {
            "department_id": 1,
            "name": "Regional",
            "description": "Proud of your country? Wear a T-shirt with a national symbol stamp!"
        },
        {
            "department_id": 2,
            "name": "Nature",
            "description": "Find beautiful T-shirts with animals and flowers in our Nature department!"
        },
        {
            "department_id": 3,
            "name": "Seasonal",
            "description": "Each time of the year has a special flavor. Our seasonal T-shirts express traditional symbols using unique postal stamp pictures."
        }
    ]
}

/类别路由的响应

{
    "data": [],
    "error": true
}

我期待数据也能与关联的对象一起出现。但它没有按预期发送数据。我哪里做错了。

这里的问题是您没有在查询中说您需要关联数据。为此,您必须在 findAll() 函数中使用 include

/* GET departments listing. */
router.get('/', function(req, res, next) {
  model.Department.findAll({
    include: [{
      model: model.Category
      as: 'categories'
    }]
  })
    .then(department => res.json({
      error: false,
      data: department
    }))
    .catch(error => res.json({
      data: [],
      error: true
    }));
});

编辑:

我看到您更改了模型的默认主键,因此您还必须在类别关联中指定它。默认情况下,Sequelize 仅适用于一种方式关联,在您的情况下,从 DeparmentCategory。 Sequelize 不知道 Category 上的 Deparment 外键,即使您定义了它。你必须定义你指的是哪个键。

Category.associate = function(models) {
  // associations can be defined here
  Category.belongsTo(models.Department,  {as: 'department', foreignKey: 'department_id'})
};