Sequelize Eager Loading Error when including related model

前端 未结 2 2365
别那么骄傲
别那么骄傲 2021-02-20 13:13

I\'m using Sequelize to make this request:

return Expense.findAll({
     include: [{
       model: ExpenseCategory
     }],
   })
  .then(expenses => res.stat         


        
2条回答
  •  没有蜡笔的小新
    2021-02-20 13:25

    I got an working answer. In this example i have a scheme where a department can have a lot of positions. The Position will include the department and the department will include its positions.

    models/Department.js

    module.exports = (sequelize, DataTypes) => 
    {
    const Sequelize = require('sequelize');
    const Department = sequelize.define('Department', 
    {
        ...
    }
    Department.associate = function(models) {
        Department.hasMany(models.Position, {
          foreignKey: 'department_id',
          as: 'positions'
        });
    };
    
    return Department;
    };
    

    models/Position.js

    module.exports = (sequelize, DataTypes) => 
    {
    const Sequelize = require('sequelize');
    const Position = sequelize.define('Position', 
    {
        ...
    }
    
    Position.associate = function(models) {
        Position.belongsTo(models.Department, {
            foreignKey: 'department_id',
            as: 'department',
            onDelete: 'CASCADE'
        });
    };
    
    return Position;
    };
    

    controllers/departmentController.js

    exports.all = async function(req, res)
    {
    return Department
        .findAll({include: [ 'positions' ]})
        .then((data) => {
            if (!data) { return res.status(400).json({status: 400,message: 'Registro não encontrado', data: data }); }
            return res.status(200).json(data);
        })
        .catch((error) => {
            return res.status(400).json({message: 'Falha no banco de dados.', data: error})
        });
    };
    

    controllers/positionController.js

    exports.all = async function(req, res)
    {
    return Position
        .findAll({include: [ 'department' ]})
        .then((data) => {
            if (!data) { return res.status(400).json({status: 400,message: 'Registro não encontrado', data: data }); }
            return res.status(200).json(data);
        })
        .catch((error) => {
            console.log(error);
            return res.status(400).json({message: 'Falha no banco de dados.', data: error})
        });
    };
    

提交回复
热议问题