【问题标题】:How to fetch associated data with models generated form Sequalize?如何使用从 Sequelize 生成的模型获取关联数据?
【发布时间】:2025-12-20 02:55:06
【问题描述】:

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

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

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

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."
        }
    ]
}

对 /category 路由的响应

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

我希望数据也会与关联的对象一起出现。但它没有按预期发送数据。我在这里做错了什么。

【问题讨论】:

    标签: mysql node.js orm sequelize.js associations


    【解决方案1】:

    这里的问题是,您并没有在查询中说您需要关联数据。为此,您必须在 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'})
    };
    

    【讨论】:

    • 谢谢,但是当我在 fetchall 中添加包含参数时,这是它生成的查询。查询无效。选择Category.category_id, Department.department_id AS Department.department_id, Department.name AS Department.name, Department.category AS categorycategoryROM 987654341@ 左外连接 department AS Department ON Category.department_department_id = Department.department_id;
    • Category.department_department_id 这部分是错误的,因为没有名为“department_department_id”的列如何解决这个问题
    • 谢谢,你拯救了我的一天!