javascript - 我想在监视器和目标表之间创建一对多关联,其中一个监视器可以有多个目标
问题描述
在我的查询中添加包含时遇到问题。我想创建两个不同的模型,其中 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"],
},
],
});
解决方案
推荐阅读
- .net - 如何在 Heroku 上直接将我的应用程序重定向到 https?
- mongodb - 过滤器的通用 TypeScript 类型
- django - 如何为用户名添加外键。Django REST 框架
- javascript - 在呈现服务器端的大型分页 DataTable 中的任何行中查找数据
- python - Django显示参考名称而不是ID
- r - 如何使用 R 中的 tidyverse 按组创建一个变量的值组合
- google-cloud-platform - 如何为服务帐户设置 Google Cloud 应用程序凭据
- node.js - 如何使用 Google Cloud Functions 和 puppeteer 将屏幕截图保存在 Google Cloud Bucket 中?
- java - 有更好的方法来检查 Top Activity 是否发生了变化?
- django - CPanel 上的 Django 部署错误“Apache 没有对该文件的读取权限。请修复相关文件权限。”