Relations help connect data between tables so you can organize and access related information easily.
Relations (OneToMany, ManyToOne, ManyToMany) in NestJS
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne, ManyToMany, JoinTable } from 'typeorm'; @Entity() export class ParentEntity { @PrimaryGeneratedColumn() id: number; @OneToMany(() => ChildEntity, child => child.parent) children: ChildEntity[]; } @Entity() export class ChildEntity { @PrimaryGeneratedColumn() id: number; @ManyToOne(() => ParentEntity, parent => parent.children) parent: ParentEntity; } @Entity() export class EntityA { @PrimaryGeneratedColumn() id: number; @ManyToMany(() => EntityB) @JoinTable() relatedEntities: EntityB[]; } @Entity() export class EntityB { @PrimaryGeneratedColumn() id: number; }
@OneToMany and @ManyToOne always work together to link two entities.
@ManyToMany needs a @JoinTable on one side to create the connection table.
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne } from 'typeorm'; @Entity() export class Author { @PrimaryGeneratedColumn() id: number; @OneToMany(() => Book, book => book.author) books: Book[]; } @Entity() export class Book { @PrimaryGeneratedColumn() id: number; @ManyToOne(() => Author, author => author.books) author: Author; }
import { Entity, PrimaryGeneratedColumn, ManyToMany, JoinTable } from 'typeorm'; @Entity() export class Student { @PrimaryGeneratedColumn() id: number; @ManyToMany(() => Course) @JoinTable() courses: Course[]; } @Entity() export class Course { @PrimaryGeneratedColumn() id: number; }
This program defines three entities: User, Post, and Tag. Users can have many posts (OneToMany). Each post belongs to one user (ManyToOne). Posts can have many tags and tags can belong to many posts (ManyToMany).
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne, ManyToMany, JoinTable } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @OneToMany(() => Post, post => post.user) posts: Post[]; } @Entity() export class Post { @PrimaryGeneratedColumn() id: number; @Column() title: string; @ManyToOne(() => User, user => user.posts) user: User; @ManyToMany(() => Tag) @JoinTable() tags: Tag[]; } @Entity() export class Tag { @PrimaryGeneratedColumn() id: number; @Column() name: string; }
Always define both sides of OneToMany and ManyToOne relations for proper data access.
Use @JoinTable only on one side of ManyToMany to avoid errors.
Relations help keep your data organized and easy to query.
Relations connect different data tables to show how they relate.
OneToMany and ManyToOne link one item to many others and back.
ManyToMany connects many items on both sides with a join table.
Practice
OneToMany relationship from an Author entity to a Book entity?Solution
Step 1: Understand the relationship direction
A OneToMany relationship means one Author has many Books.Step 2: Identify the correct decorator syntax
The decorator @OneToMany(() => Book, book => book.author) correctly sets this relation from Author to Book.Final Answer:
@OneToMany(() => Book, book => book.author) -> Option AQuick Check:
OneToMany from Author to Book = @OneToMany [OK]
- Confusing OneToMany with ManyToOne
- Using ManyToMany instead of OneToMany
- Incorrect arrow function syntax in decorator
ManyToOne relation in a NestJS entity?Solution
Step 1: Recognize the relation type
ManyToOne means many posts belong to one user.Step 2: Confirm correct decorator syntax
@ManyToOne(type => User, user => user.posts) is the correct way to define this relation.Final Answer:
@ManyToOne(type => User, user => user.posts) -> Option CQuick Check:
ManyToOne relation uses @ManyToOne decorator [OK]
- Using OneToMany instead of ManyToOne
- Wrong arrow function parameter name
- Missing inverse side property
class Student {
@ManyToMany(() => Course, course => course.students)
courses: Course[];
}
class Course {
@ManyToMany(() => Student, student => student.courses)
@JoinTable()
students: Student[];
}What will be the result of fetching a
Course with its students included?Solution
Step 1: Understand ManyToMany relation with JoinTable
ManyToMany with @JoinTable on one side creates a join table linking many students to many courses.Step 2: Fetching Course includes students array
Fetching a Course with relations loaded returns a Course object with an array of Student objects in 'students'.Final Answer:
A Course object with an array of Student objects in the 'students' property -> Option BQuick Check:
ManyToMany with @JoinTable returns array of related entities [OK]
- Expecting single object instead of array
- Forgetting @JoinTable on one side
- Confusing ManyToMany with OneToMany
@Entity()
class Post {
@OneToMany(() => Comment, comment => comment.post)
comments: Comment[];
}
@Entity()
class Comment {
@ManyToOne(() => Post, post => post.comments)
post: Post;
}What is wrong if the
comments property in Post is not initialized as an array?Solution
Step 1: Recognize relation property type
comments is an array of Comment entities, so it should be initialized to avoid undefined.Step 2: Understand runtime behavior
If not initialized, accessing or pushing to comments causes runtime errors like 'cannot read property push of undefined'.Final Answer:
It will cause runtime errors when accessing or pushing comments -> Option DQuick Check:
Uninitialized array relation causes runtime errors [OK]
- Assuming TypeORM auto-initializes arrays
- Ignoring runtime errors from undefined arrays
- Confusing property initialization with database schema
ManyToMany self-referencing relation?Solution
Step 1: Understand self-referencing ManyToMany
Users follow many users and are followed by many users, so a ManyToMany self-relation is needed.Step 2: Correctly set inverse sides and JoinTable
@Entity() class User { @ManyToMany(() => User, user => user.followers) @JoinTable() following: User[]; @ManyToMany(() => User, user => user.following) followers: User[]; }uses @ManyToMany with inverse sides and @JoinTable on one side, correctly modeling the relation.Final Answer:
Code snippet with @ManyToMany, inverse sides, and @JoinTable -> Option AQuick Check:
Self-referencing ManyToMany needs inverse sides and one @JoinTable [OK]
- Using OneToMany or ManyToOne for many-to-many
- Missing inverse side property
- Missing @JoinTable on one side
Ready to prove it?
Pass the test and this pattern moves unknown
