How to have a self-referencing many-to-many association in Sequelize?
According to Asaf in above comment, hasMany no longer works. Here is a solution using belongsToMany:
User model:
module.exports = (sequelize, DataTypes) => {
const Users = sequelize.define('Users', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
}
}, {
freezeTableName: true
});
Users.associate = function(models) {
Users.belongsToMany(models.Users, { through: models.UserUsers, as: 'Parents', foreignKey: 'parentId' });
Users.belongsToMany(models.Users, { through: models.UserUsers, as: 'Siblings', foreignKey: 'siblingId' });
};
return Users;
};
UserUsers model:
module.exports = (sequelize, DataTypes) => {
const UserUsers = sequelize.define('UserUsers', {
}, {
freezeTableName: true
});
UserUsers.associate = function(models) {
UserUsers.belongsTo(models.Users, { as: 'Parent', onDelete: 'CASCADE'});
UserUsers.belongsTo(models.Users, { as: 'Sibling', onDelete: 'CASCADE' });
};
return UserUsers;
};
Using this you set and get like this:
models.Users.findOne({ where: { name: 'name' } })
.then(u1 => {
models.Users.findOne({ where: { name: 'name2'} })
.then(u2 => {
u2.addSibling(u1);
// or if you have a list of siblings you can use the function:
u2.addSiblings([u1, ...more siblings]);
});
});
and
models.Users.findOne({ where: { name: 'name'} })
.then(person => {
person.getSiblings()
.then(siblings => { console.log(siblings) });
});
References: Sequelize docs
What have you tried?
How about this:
var Task = sequelize.define('Task', {
name: Sequelize.STRING
});
Task.belongsToMany(Task, { as: 'children', foreignKey: 'ParentTaskId', through: 'ParentTasks' });
Task.belongsToMany(Task, { as: 'parents', foreignKey: 'TaskId', through: 'ParentTasks' });
please refer to https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html