如何使用通过Sequalize生成的模型来获取关联数据?

时间:2019-03-27 14:03:53

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

我一直在开发带有MySQL支持且以Sequelize作为ORM的NodeJs后端应用程序。我试图通过调用我创建的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
}

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

1 个答案:

答案 0 :(得分:1)

这里的事情是您不是在查询中说需要关联数据。为此,您必须在include函数内部使用findAll()

/* 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
    }));
});

编辑:

我看到您更改了模型的默认主键,因此还必须在Category关联上指定它。默认情况下,Sequelize仅适用于从DeparmentCategory的情况下的单向关联。即使您定义了Deparment上的Category外键,Sequelize也不知道。您必须定义要指向的键。

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