【发布时间】: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