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",
}
}
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'
}]
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With