Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize: How associate two fields from a table another table

I have the following table settings from my sequelize.

const Accounts = sequelize.define('Accounts', {
  name: DataTypes.STRING,
});

const Transfers = sequelize.define('Transfers', {
  value: {
    type: DataTypes.DECIMAL(10, 2),
    defaultValue: 0,
  },
  accountIdFrom: DataTypes.INTEGER,
  accountIdTo: DataTypes.INTEGER,
});

Transfers.belongsTo(Accounts, { foreignKey: 'accountIdFrom' });
Transfers.belongsTo(Accounts, { foreignKey: 'accountIdTo' });

const data = await Transfers.findAll({
  include: [{ model: Accounts }]
});

Return:

{
  "id": 1,
  "value": "10.00",
  "accountIdFrom": 1,
  "accountIdTo": 2,
  "Account": {
    "id": 2,
    "name": "Banco Neon",
  }
}

I tried to use the association setting this way, but the sequelize always associates with just one field, and I want it to either show for both fields. accountIdFrom andacountIdTo.

The expected return should be something like this, but, it is not working:

{
  "id": 2,
  "value": "10.00",
  "accountIdFrom": 2,
  "accountIdTo": 1,
  "AccountFrom": {
    "id": 2,
    "name": "Bank Two",
  },
  "AccountTo": {
    "id": 1,
    "name": "Bank One",
  }
}
like image 919
David Costa Avatar asked Sep 18 '25 19:09

David Costa


1 Answers

You have to use as: instead of foreignKey:

Transfers.belongsTo(Accounts, { as: 'accountFrom', onDelete: 'cascade', onUpdate: 'no action' });
Transfers.belongsTo(Accounts, { as: 'accountTo', onDelete: 'cascade', onUpdate: 'no action' });

This will give you on your Accounts model the columns accountFromId and accountToId. So when you need to include the models you're going to do it like this:

Transfers.find( {
  where: {},
  include: [{
    model: db.Accounts,
    as: 'accountFrom'
  },{
    model: db.Accounts,
    as: 'accountTo'
  }]
})
like image 67
Ellebkey Avatar answered Sep 20 '25 09:09

Ellebkey