Junior — Middle
How is the management of relationships between tables implemented in TypeORM?
sobes.tech AI
Answer from AI
In TypeORM, managing relationships between tables is done using special decorators that describe the type of relationship between entities (tables). The main types of relationships:
@OneToOne— one-to-one@OneToMany— one-to-many@ManyToOne— many-to-one@ManyToMany— many-to-many
Each of these decorators is applied to a property of the entity class, indicating which other entity it is related to and how. For bidirectional relationships, the inverse property is usually specified.
Example of a "one-to-many" relationship:
@Entity()
class User {
@PrimaryGeneratedColumn()
id: number;
@OneToMany(() => Photo, photo => photo.user)
photos: Photo[];
}
@Entity()
class Photo {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(() => User, user => user.photos)
user: User;
}
Thus, TypeORM automatically manages foreign keys and loading of related data.