尝试使用https://stackoverflow.com/a/4378624对类似于Sequelize Typescript中的联接表选项的配偶关系进行建模。
这是可行的,但看起来不太好。为了查找某人是否在婚姻中,看起来我必须同时加入表中的person1Id
和person2Id
(在我的示例中,@HasOne
在表中定义了两次) Person
模型)。
// Marriage Model
@Column
person1Id: number;
@BelongsTo(() => Person, { foreignKey: { allowNull: false, name: 'person1Id' }, onUpdate: 'CASCADE', onDelete: 'CASCADE' })
person1: Person;
@Column
person2Id: number;
@BelongsTo(() => Person, { foreignKey: { allowNull: false, name: 'person2Id' }, onUpdate: 'CASCADE', onDelete: 'CASCADE' })
person2: Person;
// marriage date, other properties, etc.
// Person Model
@HasOne(() => Marriage, { foreignKey: 'person1Id' })
marriage1: Marriage;
@HasOne(() => Marriage, { foreignKey: 'person2Id' })
marriage2: Marriage;
// really the person only has one marriage, but needed if `Person.id === Marriage.person2Id`
我已经尝试了以下方法,但是如果联接表中的person2Id
不在婚姻中。
// DOES NOT WORK
// Person Model
@HasOne(() => Marriage)
marriage: Marriage;
// Retrieving it somewhere else
somePerson = await Person.findOne<Person>({
include: [
{
model: Marriage,
as: 'marriage'
}
], where: { id: personId }
});
// somePerson.marriage is `undefined` if `Person.id === Marriage.person2Id`!
任何关于如何使这个更好的想法都受到赞赏。