Performance: Relations (OneToMany, ManyToOne, ManyToMany)
This affects database query performance and server response time, impacting how fast data loads and updates in the app.
const users = await userRepository.find({ relations: ['posts'] });
const users = await userRepository.find(); for (const user of users) { user.posts = await postRepository.find({ where: { user: { id: user.id } } }); }
| Pattern | Database Queries | Query Count | Response Time Impact | Verdict |
|---|---|---|---|---|
| N+1 Query Pattern | Multiple separate queries | N+1 queries | High response time, slower LCP | [X] Bad |
| Eager Loading Relations | Single joined query | 1 query | Low response time, faster LCP | [OK] Good |
| ManyToMany without indexes | Join queries on large tables | 1 query | Potentially slow if unindexed | [!] OK |
| ManyToMany with indexed join table | Optimized join query | 1 query | Fast response, scalable | [OK] Good |
OneToMany relationship from an Author entity to a Book entity?ManyToOne relation in a NestJS entity?class Student {
@ManyToMany(() => Course, course => course.students)
courses: Course[];
}
class Course {
@ManyToMany(() => Student, student => student.courses)
@JoinTable()
students: Student[];
}Course with its students included?@Entity()
class Post {
@OneToMany(() => Comment, comment => comment.post)
comments: Comment[];
}
@Entity()
class Comment {
@ManyToOne(() => Post, post => post.comments)
post: Post;
}comments property in Post is not initialized as an array?ManyToMany self-referencing relation?@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.Pass the test and this pattern moves unknown