'Sequelize Many to Many Self association query to fetch non directional relations
I have a model 'Boy' in which I want to create many to many self association such that boy1 and boy2 are brothers.
Model Boy
const Sequelize = require('sequelize');
const Boy = sequelize.define('boy', {
name: Sequelize.STRING,
age: Sequelize.INTEGER,
});
module.exports.Boy;
M:N self association:
const Boy = require('./boy');
const Sequelize = require('sequelize');
const Brother = sequelize.define('brother', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
});
Boy.belongsToMany(Boy, {through Brother, as: "Brother", foreignKey: 'brother_1_id', otherKey: 'brother_2_id'});
and then I want to fetch all brothers to boy1 using below query:
Boy.findByPk(id, {
include: [
{
model: Boy,
as: "Boy",
attributes: ["name", "age"],
},
],
}).then( boy => console.log(boy))
Then I am adding boy2 as a brother to boy1 and boy1 as brother to boy3.
but when I am fetching brothers of boy1 using above mentioned query, I am only getting boy2 and not boy3.
Is there a way that I can define the relations so that when I fetch brothers of boy1 I would get both boy2 and boy3 ?
Solution 1:[1]
I solved this by adding following line to M:N self association:
Boy.belongsToMany(Boy, {through Brother, as: "ReverseBrother", foreignKey: 'brother_2_id', otherKey: 'brother_1_id'});
and then by including following lines in query:
Boy.findByPk(id, {
include: [
{
model: Boy,
as: "Boy",
attributes: ["name", "age"],
},
],
include: [
{
model: Boy,
as: "ReverseBrother",
attributes: ["name", "age"],
},
]
}).then( boy => console.log(boy))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JayantSeth |
