首页 > 解决方案 > 我想在监视器和目标表之间创建一对多关联,其中一个监视器可以有多个目标

问题描述

在我的查询中添加包含时遇到问题。我想创建两个不同的模型,其中 Monitor 可以有多个目的地。我四处搜索并试图找到解决方法,但不幸的是我找不到任何合适的解决方案。

Monitor.js

const Monitor = db.define("monitor", {
  monitor_name: {
    type: Sequelize.STRING,
    required: true,
    unique: true,
  },
  destination: {
    type: Sequelize.INTEGER,
    references: {
      model: Destination, // <<< Note, its table's name, not object name
      key: "id", // <<< Note, its a column name
    },
  }
});

Monitor.associate = function (models) {
  Monitor.hasMany(models.Destination, {
    foreignKey: "id",
    as: "monitorId",
  });
};

Monitor.sync().then(() => {
  console.log("Monitor Model Created");
});

module.exports = Monitor;

目的地.js

const Destination = db.define("destination", {
  destination_name: {
    type: Sequelize.STRING,
    required: true,
    unique: true,
  }
});

Destination.associate = (models) => {
  Destination.belongsTo(models.Monitor);
};

Destination.sync().then(() => {
  console.log("Destination Model Created");
});

module.exports = Destination;

let data = await Monitors.findOne({
          where: { id: monitor_ID },
          include: [
            {
              model: Destination,
              attributes: ["destination_name"],
            },
          ],
        });

标签: javascriptnode.jspostgresqlsequelize.js

解决方案


推荐阅读