0
0
NestJSframework~10 mins

Relations (OneToMany, ManyToOne, ManyToMany) in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Relations (OneToMany, ManyToOne, ManyToMany)
Define Entities
Add Relation Decorators
OneToMany <-> ManyToOne Setup
ManyToMany Setup
Use Repository to Save & Query
Relations Loaded or Joined
Access Related Data
This flow shows how to define entities, set up relations with decorators, save and query data, and access related entities in NestJS.
Execution Sample
NestJS
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne } from 'typeorm';

@Entity()
export class Author {
  @PrimaryGeneratedColumn() id: number;
  @Column() name: string;
  @OneToMany(() => Book, book => book.author) books: Book[];
}

@Entity()
export class Book {
  @PrimaryGeneratedColumn() id: number;
  @Column() title: string;
  @ManyToOne(() => Author, author => author.books) author: Author;
}
Defines Author and Book entities with OneToMany and ManyToOne relations between them.
Execution Table
StepActionEntity StateRelation SetupResult
1Create Author instanceAuthor { id: undefined, name: 'Alice', books: [] }No relations yetAuthor object ready
2Create Book instanceBook { id: undefined, title: 'NestJS Guide', author: undefined }No relations yetBook object ready
3Assign author to bookBook.author = Author instanceManyToOne relation setBook linked to Author
4Add book to author's books arrayAuthor.books = [Book instance]OneToMany relation setAuthor linked to Book
5Save Author and Book to DBEntities persistedRelations saved via foreign keysData stored with relations
6Query Book with author relationBook loaded with authorRelation joinedBook.author accessible
7Query Author with books relationAuthor loaded with books arrayRelation joinedAuthor.books accessible
8Exit--Relations fully established and accessible
💡 All entities saved and relations correctly linked in database
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
Author instanceundefined{ id: undefined, name: 'Alice', books: [] }{ id: undefined, name: 'Alice', books: [] }{ id: undefined, name: 'Alice', books: [] }{ id: undefined, name: 'Alice', books: [Book instance] }Persisted with id
Book instanceundefinedundefined{ id: undefined, title: 'NestJS Guide', author: undefined }{ id: undefined, title: 'NestJS Guide', author: Author instance }{ id: undefined, title: 'NestJS Guide', author: Author instance }Persisted with id
Key Moments - 3 Insights
Why do we assign the author to the book and also add the book to the author's books array?
Because OneToMany and ManyToOne relations are two sides of the same link. Assigning both ensures the relation is complete in memory before saving, as shown in steps 3 and 4 of the execution_table.
What happens if we save only the book without adding it to the author's books array?
The database will store the foreign key from book to author, but the author's books array in memory won't reflect the relation until reloaded, as the OneToMany side is not updated (see step 4).
How does ManyToMany differ from OneToMany/ManyToOne in setup?
ManyToMany uses a join table to link entities on both sides equally, unlike OneToMany/ManyToOne which uses a foreign key on the ManyToOne side. This is a separate step after OneToMany/ManyToOne setup.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what relation is being set?
AOneToMany from Author to Book
BManyToOne from Book to Author
CManyToMany between Author and Book
DNo relation set yet
💡 Hint
Check the 'Relation Setup' column at step 3 in execution_table
At which step does the Author's books array get updated?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look for 'Author.books = [Book instance]' in the 'Entity State' column
If we skip adding the book to the author's books array, what will happen?
AThe relation will be fully saved and accessible both ways
BThe book will not save at all
CThe database will save the relation but Author.books in memory will be empty
DAn error will occur during save
💡 Hint
Refer to key_moments explanation about incomplete relation setup
Concept Snapshot
Relations in NestJS with TypeORM:
- Use @OneToMany on the 'one' side and @ManyToOne on the 'many' side
- Both sides must reference each other for full relation
- ManyToMany uses @ManyToMany with a join table
- Save entities with relations to persist foreign keys
- Query with relations to access linked data easily
Full Transcript
This visual execution trace shows how to set up relations in NestJS using TypeORM decorators. First, entities are defined with @Entity and columns. Then, relations are added using @OneToMany and @ManyToOne decorators referencing each other. Instances of entities are created and linked by assigning the related objects on both sides. Saving these entities persists the relations in the database via foreign keys. Querying with relations loads the linked data for easy access. Key moments clarify why both sides must be assigned and how ManyToMany differs. The quiz tests understanding of relation setup steps and effects of incomplete linking.