0

Trying to model a spouse relationship similar to the join table option from https://stackoverflow.com/a/4378624 using Sequelize Typescript.

It kind of works, but doesn't seem very nice. In order to find whether a person is in a marriage, it looks like I have to join on both person1Id and person2Id in the table (in my example, having @HasOne defined twice in the Person model).

// 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`

I've tried the following, but doesn't retrieve a marriage if they are person2Id in the join table.

// 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`!

Any ideas on how to make this nicer is appreciated.

ahong
  • 1,041
  • 2
  • 10
  • 22

1 Answers1

0

I offer implement it just by Using a Foreign Key, maybe meriage model will not be used at all. some examples here

  • I know there is multiple options (see point 5 of the link you posted) and also the different options from the linked stack overflow question. However, this doesn't answer the question. Maybe you could have posted it as a comment. – ahong Jun 12 '19 at 05:37