如何在 Sequelize 中建立自引用的多对多关联? [英] How to have a self-referencing many-to-many association in Sequelize?

查看:42
本文介绍了如何在 Sequelize 中建立自引用的多对多关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Task 的模型,它可以有许多父任务(多个祖先)和/或子任务.

I have a model called Task, which can have many parent tasks (multiple ancestors) and/or child tasks.

如果我要在没有 Sequelize 的情况下对此进行建模,我将有一个名为 ParentTasks 的表,其中包含一个 ParentTaskId 和一个 TaskId确定关系和以 id 作为主键的 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.

使用 Sequelize,这可能吗?我尝试了很多不同的排列和组合,但都没有达到我想要的效果.

Using Sequelize, is this possible? I've tried so many different permutations and combinations, but none lead to what I want.

任何帮助将不胜感激.

谢谢.

推荐答案

根据以上评论中的 Asaf 所述,hasMany 不再有效.这是使用belongsToMany的解决方案:

According to Asaf in above comment, hasMany no longer works. Here is a solution using belongsToMany:

用户模型:

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;
};

用户用户模型:

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]);
  });
});

models.Users.findOne({ where: { name: 'name'} })
.then(person => {
  person.getSiblings()
  .then(siblings => { console.log(siblings) });
});

参考:Sequelize 文档

这篇关于如何在 Sequelize 中建立自引用的多对多关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆