Search code examples
typeorm

Can I avoid using the whole entities for data on related tables with TypeOrm?


I have those sample entities with a N:N relation on TypeOrm:

export default class Model extends BaseEntity {
  @ManyToMany(type => Market, market => market.id,{ onDelete: 'CASCADE'})
  @JoinTable({ 'name': 'model_enabled_markets' })
  marketsEnabled: Market[];
  //...
}
export default class Market extends BaseEntity {
  @ManyToMany<Model>(type => Model, model => model.id,{ onDelete: 'RESTRICT'})
  enabledModels: Promise<Model[]>;
  //...
}

When about to save a new Model instance to the database, if I have the ids I need to place on the marketsEnabled, is there any way I can use them directly? Or do I need to query the required Markets with those IDs, and assign an array with them?


Solution

  • TypeORM expects that all entity objects (will) exist in a relation array (this is necessary, for example, because of the cascade option). Besides that, typescript also expects an object that matches that of the model, so it is probably not enough to just pass an object with an id field only.

    To manipulate the join table directly, it is best to create it yourself as an entity class. This allows you to add or remove individual foreign id rows without first loading all relation entries in the navigation properties (relation arrays) of linked entity objects.