我怎样才能拥有一个 Sequelize 复合键(非唯一,唯一)对,然后用它来映射关联?
How can I have a Sequelize composite key a (non-unique, unique) pair and then use it to map associations?
我的 SQL 数据库中有这些关系。有两种实体类型 A 和 B。这些实体是资源的所有者,我通过映射 table 来管理它。关系是:
实体 A 有一个或多个所有者条目。
实体 B 有一个或多个所有者条目。
每个所有者条目都有零个或一个实体 A 条目。
每个所有者条目都有零个或一个实体 B 条目。
每个资源都有零个或多个所有者。
每个所有者条目跟踪一个资源。
我正在使用它来模拟拥有资源的个人和团体。问题是当我去使用 ORM 时它抱怨我没有给出所有者和实体之间的关联。我不太确定如何使用 Sequelize 执行此操作。我想做的是有一个像这样的复合键:
(entity_type, entity_id)
其中 entity_type 来自枚举 (EntityA, EntityB),entity_id 是对应于 table 中任一记录的 ID。这样我就可以保证组合键是唯一的。但同样,我不太确定如何通过 Sequelize 实现它。
关联时,我们可以使用where
条件,如下代码。
型号:Owner.js
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Owner extends Model {
static associate(models) {
// define association here
this.belongsTo(models.EntityA, {
foreignKey: "entity_id",
as: "A",
where: { entity_type: 0 }
});
this.belongsTo(models.EntityB, {
foreignKey: "entity_id",
as: "B",
where: { entity_type: 1 }
});
}
}
Owner.init({
entity_type: DataTypes.INTEGER,
entity_id: DataTypes.INTEGER,
}, {
sequelize,
modelName: "Owner"
});
return Owner;
};
db.Owner.findAll({
include: 'A', 'B'
});
我的 SQL 数据库中有这些关系。有两种实体类型 A 和 B。这些实体是资源的所有者,我通过映射 table 来管理它。关系是:
实体 A 有一个或多个所有者条目。 实体 B 有一个或多个所有者条目。
每个所有者条目都有零个或一个实体 A 条目。 每个所有者条目都有零个或一个实体 B 条目。
每个资源都有零个或多个所有者。 每个所有者条目跟踪一个资源。
我正在使用它来模拟拥有资源的个人和团体。问题是当我去使用 ORM 时它抱怨我没有给出所有者和实体之间的关联。我不太确定如何使用 Sequelize 执行此操作。我想做的是有一个像这样的复合键:
(entity_type, entity_id)
其中 entity_type 来自枚举 (EntityA, EntityB),entity_id 是对应于 table 中任一记录的 ID。这样我就可以保证组合键是唯一的。但同样,我不太确定如何通过 Sequelize 实现它。
关联时,我们可以使用where
条件,如下代码。
型号:Owner.js
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Owner extends Model {
static associate(models) {
// define association here
this.belongsTo(models.EntityA, {
foreignKey: "entity_id",
as: "A",
where: { entity_type: 0 }
});
this.belongsTo(models.EntityB, {
foreignKey: "entity_id",
as: "B",
where: { entity_type: 1 }
});
}
}
Owner.init({
entity_type: DataTypes.INTEGER,
entity_id: DataTypes.INTEGER,
}, {
sequelize,
modelName: "Owner"
});
return Owner;
};
db.Owner.findAll({
include: 'A', 'B'
});