Ni3
Ni3

Reputation: 286

SequelizeEagerLoadingError in associated models

I'm getting an issue when I add include in my query, and I can't figure out why. I have two models: User and Transaction

User

    module.exports = (sequelize, DataTypes) => {
      var User = sequelize.define('User', {
        firstName: DataTypes.STRING,
        lastName: DataTypes.STRING,
        email: DataTypes.STRING
      }, {});
      User.associate = function(models) {
        User.hasMany(models.Transaction, {
          foreignKey: 'senderId',
          as: 'sender',
        }),
        User.hasMany(models.Transaction, {
          foreignKey: 'receiverId',
          as: 'receiver',
        })
      };
      return User;
    };

Transaction

  module.exports = (sequelize, DataTypes) => {
    var Transaction = sequelize.define('Transaction', {
      amount: DataTypes.INTEGER
    }, {});
    Transaction.associate = function(models) {
      Transaction.belongsTo(models.User, {
        foreignKey: 'senderId'
      }),
      Transaction.belongsTo(models.User, {
        foreignKey: 'receiverId'
      })
    };
    return Transaction;
  };

Both senderId and receiverId are available in db after migration.

Attempted query:

  Transaction
    .findAll({
      where: { senderId: req.params.userId },
      include: [{
        model: User,
        as: 'sender',
      },{
        model: User,
        as: 'receiver',
      }],
    })

Expected Result:

  {
    "transactions": [
      {
        "id": 2,
        "amount": 300,
        "sender": {
          "id": 2,
          "firstName": "John",
          "lastName": "Doe",
          "email": "[email protected]",
        },
        "receiver": {
          "id": 3,
          "firstName": "John1",
          "lastName": "Doe1",
          "email": "[email protected]",
        }
      },
      {
        "id": 3,
        "amount": 900,
        "sender": {
          "id": 2,
          "firstName": "John",
          "lastName": "Doe",
          "email": "[email protected]",
        },
        "receiver": {
          "id": 3,
          "firstName": "John1",
          "lastName": "Doe1",
          "email": "[email protected]",
        }
      }
    ]
  }

But I'm getting the error: SequelizeEagerLoadingError

Is their something wrong with association or query?

Upvotes: 2

Views: 5409

Answers (1)

Harsh
Harsh

Reputation: 69

You'll need to add an alias to one or both of those associations, currently they are overwriting eachother. Something like:

module.exports = (sequelize, DataTypes) => {
  var Transaction = sequelize.define('Transaction', {
    amount: DataTypes.INTEGER
  }, {});
  Transaction.associate = function(models) {
    Transaction.belongsTo(models.User, {
      as: 'sender',
      foreignKey: 'senderId'
    }),
    Transaction.belongsTo(models.User, {
      as: 'receiver',
      foreignKey: 'receiverId'
    })
  };
  return Transaction;
};

Upvotes: 1

Related Questions