I have a model called Task, which can have many parent tasks (multiple ancestors) and/or child tasks.
If I were to model this without Sequelize, I'd have a table called ParentTasks, which would have a ParentTaskId and a TaskId to determine the relationship and a Tasks table with an id as the primary key.
Using Sequelize, is this possible? I've tried so many different permutations and combinations, but none lead to what I want.
Any help would be appreciated.
Thanks.
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
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
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