Creating relationships in TypeORM involves several key steps to ensure that the relationships between database models are accurately defined and implemented. Below, I will explain in detail how to create the most common relationship types: One-to-Many and Many-to-One.
1. Defining Entities
First, define each entity involved in the relationship. For example, assume we have a User entity and a Photo entity, where a user can have multiple photos, but each photo belongs to only one user.
User Entity
typescriptimport { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm"; import { Photo } from "./Photo"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @OneToMany(() => Photo, photo => photo.user) photos: Photo[]; }
Photo Entity
typescriptimport { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"; import { User } from "./User"; @Entity() export class Photo { @PrimaryGeneratedColumn() id: number; @Column() url: string; @ManyToOne(() => User, user => user.photos) user: User; }
2. Establishing Relationships
In the above code, the User entity declares its relationship with the Photo entity using the @OneToMany decorator, indicating that a user can have multiple photos. Correspondingly, the Photo entity declares its relationship with the User entity using the @ManyToOne decorator, indicating that each photo belongs to one user.
3. Using Relationships
After establishing the relationships, you can leverage these relationships in your business logic to load, insert, and update data.
Saving Data
typescriptimport { createConnection, getRepository } from "typeorm"; import { User } from "./User"; import { Photo } from "./Photo"; createConnection(/*database configuration*/).then(async connection => { const userRepository = getRepository(User); const photoRepository = getRepository(Photo); const user = new User(); user.name = "John Doe"; await userRepository.save(user); const photo = new Photo(); photo.url = "http://example.com/photo.jpg"; photo.user = user; await photoRepository.save(photo); }).catch(error => console.log(error));
Loading Data
typescriptuserRepository.find({ relations: ["photos"] }).then(users => { console.log(users); });
In this example, we first save a user and their photo, then use the relations option to load the user along with all their photos during retrieval.
Summary
Establishing correct relationships is essential for ensuring data consistency and integrity. In TypeORM, properly using decorators to mark relationships and handling these relationships appropriately within business logic forms the foundation for effective data operations. I hope this example helps you grasp the fundamental methods for creating and utilizing relationships in TypeORM.