Sequelize:通过另一个 table 与自己建立多对多关系?

Sequelize: many-to-many relationship to self, through another table?

sequelize.js 中,是否可以通过另一个 table 将 table 与其自身相关联?

我正在尝试创建一个基本的图形模型。我有两个相关的 table:NodeEdge。我希望通过 Edge.

构建从 Node 到自身的多对多关系

示例:有一个 Node 名为“Dave”,一个 Edgepredicate “Loves”,另一个 Node 名为“Sarah”。

Nodetable中,id是主键。在 Edge table 中,字段 subject_node_iddirect_object_node_id 应该指向节点 id.

这是我想要的快速简单的 ERD:

这是我迄今为止最好的尝试。以下代码创建 table 列 OK,但未按预期创建行。 create 方法可能完全错误;例如,应该有设置predicate的方法,但我不知道放在哪里:

const { Sequelize } = require("sequelize");

(async () => {
  try {
    const db = await new Sequelize({
      dialect: "sqlite",
      storage: "./db/db.db",
    });
    
    const Node = await db.define("node", {
      name: {
        type: Sequelize.STRING,
      },
    });
    
    const Edge = await db.define("edge", {
      subject_node_id: {
        type: Sequelize.INTEGER,
      },
      predicate: {
        type: Sequelize.STRING,
      },
      direct_object_node_id: {
        type: Sequelize.INTEGER,
      },
    });

    await Node.sync({ force: true });
    await Edge.sync({ force: true });

    await Node.belongsToMany(Node, {
      through: "Edge",
      as: "subjects",
      foreignKey: "id",
      otherKey: "subject_node_id"
    });

    await Node.belongsToMany(Node, {
      through: "Edge",
      as: "direct_objects",
      foreignKey: "id",
      otherKey: "direct_object_node_id"
    });
    
    await Node.create(
      {
        name: "Dave",
        // Loves ??
        subjects: [{
          name: "Sarah"
        }]
      },
    );

    console.log("created");
  } catch (error) {
    console.error(error);
  }
})();

我确实找到了 ,但接受的答案并没有完全到达那里。还有其他想法吗?谢谢。

我想通了:

const { Sequelize, DataTypes } = require("sequelize");

(async () => {
  try {
    const db = await new Sequelize({
      dialect: "sqlite",
      storage: "./db/db.db",
    });

    const Node = db.define("node", {
      name: DataTypes.STRING,
    });
    const Edge = db.define("edge", {
      subjectId: DataTypes.INTEGER,
      predicate: DataTypes.STRING,
      dobjectId: DataTypes.INTEGER,
    });

    await Node.belongsToMany(Node, {
      through: Edge,
      as: "subjects",
      foreignKey: "dobjectId",
    });

    await Node.belongsToMany(Node, {
      through: Edge,
      as: "dobjects",
      foreignKey: "subjectId",
    });

    await db.sync({force: true});

    const dave = await Node.create({ name: "Dave" });
    const sarah = await Node.create({ name: "Sarah" });

    await dave.addDobject(sarah, { through: {
      predicate: "Loves"
    }});
    await sarah.addDobject(dave, { through: {
      predicate: "Loves"
    }});

    const result = await Node.findOne({
      where: { name: "sarah" },
      include: ["subjects", "dobjects"],
    });
    console.log(result);

    console.log("created");
  } catch (error) {
    console.error(error);
  }
})();