Sequelize Eager Loading Error when including related model

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

I\'m using Sequelize to make this request:

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


        
2条回答
  •  旧时难觅i
    2021-02-20 13:25

    Just change this sections

    classMethods: {
        associate: function (models) {
            ExpenseCateogory.hasMany(models.Expense, {
                foreignKey: 'expenseCategoryId'
            });
        }
    }
    

    to

    ExpenseCategory.associate = (models) => {
        ExpenseCategory.hasMany(models.style,{
            as:'expensecategories'
        });
    }
    

    so the model in full will follow this structure and the other models as well

    const ExpenseCategory = sequelize.define('ExpenseCategory', {
        id: {
            allowNull: false,
            autoIncrement: true,
            primaryKey: true,
            type: DataTypes.INTEGER
        },
        category: {
            allowNull: false,
            type: DataTypes.STRING
        }
    });
    ExpenseCategory.associate = (models) => {
        ExpenseCategory.hasMany(models.style,{
            as:'expensecategories'
        });
    }
    return ExpenseCategory;
    

    This is with reference to this youtube video https://www.youtube.com/watch?v=SaVxJrTRkrI and this example from github for sequelize examples on associations for models https://github.com/sequelize/express-example/tree/master/models

提交回复
热议问题