Search code examples
typescriptsqlitetypeorm

TypeORM: many-to-one relation targeting different entity types


I'm trying to model the following situation in TypeORM:

[ItemContainer]-(0..1)---(0..n)-[ContainableItem]-(0..n)---(0..1)-[ItemLocation]

Or in words: A ContainableItem can be in either an ItemContainer or at an ItemLocation. In practice it won't be able to appear in both at the same time, but this is not important for the problem at hand. Additionally, I'd like to point out that there is no overlap between ItemContainer and ItemLocation, they are completely different entities.

I tried modelling this situation by putting a one-to-many on both ItemContainer and ItemLocation pointing to ContainableItem.

But I'm having difficulties modelling the many-to-one relation from the point of view of the ContainableItem. How can I tell TypeORM that ContainableItem.parent points to either an ItemContainer or an ItemLocation?

ContainableItem Schema (snippet)

{
  ...
  relations: {
    parent: {
      type: 'many-to-one',
      target: ItemContainer.name || ItemLocation.name,
      inverseSide: nameof<ItemContainer |ItemLocation >((cl) => cl.items),
    },
  },
  ...
}

Solution

  • As I understand you have to create 2 columns that can be nullable for both ItemContainer and ItemLocation. then if item available in location you can put location id and leave item container null or if item in itemcontainer then you can put container id for there and leave null in item location. I think this is what you want.