Repositories, Relations & Querying
Repositories, Relations & Querying
A repository is TypeORM's interface for reading and writing one entity. NestJS injects it for you, and you call its methods from a service. This lesson covers everyday CRUD, defining relations between entities, and building more advanced queries.
Injecting a repository
Use @InjectRepository() to get a typed repository for an entity registered with forFeature():
Everyday CRUD
create() only builds an entity instance in memory (and runs default values) — it does not touch the database. save() is what persists it. Forgetting save() is a classic "why isn't it saving?" bug.
Defining relations
Relations connect entities. TypeORM provides decorators for each cardinality. A one-to-many / many-to-one pair, for example a user with many posts:
Other relation decorators are @OneToOne() and @ManyToMany() (the latter creates a join table automatically).
Loading relations
Relations are not loaded by default — you ask for them with the relations option:
relations or a JOIN in the query builder) instead of lazily inside a loop.
The query builder for complex queries
For anything beyond simple finds — joins, aggregates, conditional filters — use the query builder:
:active), never string concatenation. The query builder parameterises values, which prevents SQL injection. Building a WHERE clause by concatenating user input is a serious vulnerability.
Summary
Inject a Repository<Entity> with @InjectRepository() and use create/save/find/update/delete for CRUD (remember save() persists). Define relations with @OneToMany/@ManyToOne/@ManyToMany, load them with the relations option, and avoid N+1 queries. Use the query builder with bound parameters for complex, safe queries. Next: managing schema changes with migrations.