How to create One to Many and Many to Many relationships in TypeORM
1 min readJul 14, 2020
What are one-to-many relations
One-to-many is a relation where A contains one instance of B, and B contain multiple instances of A. Let’s take for example and entities. Customer can have multiple contacts, and each contact can have one customer.
What are many-to-many relations
Many-to-many is a relation where A contains multiple instances of B, and B contain multiple instances of A. Let’s take for example and entities. Customer can have multiple schedules, and each schedule can have multiple customers.
The code
I am manually creating the schedules_customers table, referring to ScheduleCustomer.
Saving many-to-many relations
Loading many-to-many relations
In the Schedule class where I configure the many-to-many relationship add {eager: true}, like this:
@ManyToMany(() => Customer, customer => customer.schedules, { eager: true })
Code repository: