1

I have a user with three foreign keys. Using sequelize how do i get the details of the reference when i use findAll

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define(
    'user',
    {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
      name: {
        type: DataTypes.STRING,
      },
      bank: {
        type: DataTypes.STRING,
        references: {
          model: 'summary',
          key: 'id'
        }
      }
    },
    {
    
      freezeTableName: true,
      tableName: 'user'
    }
  );

  return User;
};

Loan model

module.exports = (sequelize, DataTypes) => {
  const Loan = sequelize.define(
    'loan',
    {
      loan_id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
      amoount: {
        type: DataTypes.FLOAT,
        references: {
          model: 'provider',
          key: 'id'
        }
      },
   user_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'user',
          key: 'id'
        }
      },
      guarantor_one_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'user',
          key: 'id'
        }
      },
      guarantor_two_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'user',
          key: 'id'
        }
      }
    },
    {
      freezeTableName: true,
      tableName: 'loan'
    }
  );
  Loan.associate = models => {
    Loan.belongsTo(models.User, { foreignKey: 'user_id' });
    Loan.belongsTo(models.User, { foreignKey: 'guarantor_one_id' });
    Loan.belongsTo(models.User, { foreignKey: 'guarantor_two_id' });
  };
  return Loan;
};

What is the best way to retrieve all the data of the user_id, guarantor_one_id and guarantor_two_id using Loan.findAll.

Thank you.

const loan = Loan.findAll({where : {user_id: user_id}, include: [ model: User]});

Its only showing only one user details in the loan, i am expecting it to return the user_id, guarantor_one_id and guarantor_two_id reference on the user table with their attributes.

1 Answers1

1

I just need to use aliases for associations in order to distinguish them from each other and then to indicate an alias (aliases) explicitly in the include option to help Sequelize to understand what foreign key/association to use:
associations with aliases

  Loan.associate = models => {
    Loan.belongsTo(models.User, { foreignKey: 'user_id', as: 'user' });
    Loan.belongsTo(models.User, { foreignKey: 'guarantor_one_id', as: 'guarantorOne' });
    Loan.belongsTo(models.User, { foreignKey: 'guarantor_two_id', as: 'guarantorTwo' });
  };

usage:

const loan = Loan.findAll({
  where: {
    user_id: user_id},
    include: [{
      model: User,
      as: 'user'
    },{
      model: User,
      as: 'guarantorOne'
    },{
      model: User,
      as: 'guarantorTwo'
    }
    ]
  }
);
Anatoly
  • 20,799
  • 3
  • 28
  • 42