在TypeORM中存根嵌套存储库的方法是通过使用TypeORM的Repository模式和Entity的关系来实现。存根嵌套存储库是指在一个实体中嵌套另一个实体的存储库。
以下是在TypeORM中实现存根嵌套存储库的步骤:
@Entity()
export class ParentEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(type => ChildEntity, child => child.parent, { cascade: true })
children: ChildEntity[];
}
@Entity()
export class ChildEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToOne(type => ParentEntity, parent => parent.children)
parent: ParentEntity;
}
@EntityRepository(ParentEntity)
export class ParentRepository extends Repository<ParentEntity> {
async saveWithChildren(parent: ParentEntity): Promise<ParentEntity> {
const childRepository = getRepository(ChildEntity);
parent.children = await Promise.all(parent.children.map(child => childRepository.save(child)));
return this.save(parent);
}
}
@EntityRepository(ChildEntity)
export class ChildRepository extends Repository<ChildEntity> {}
import { createConnection } from "typeorm";
import { ParentEntity, ChildEntity } from "./entities";
import { ParentRepository, ChildRepository } from "./repositories";
createConnection({
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "password",
database: "database",
entities: [ParentEntity, ChildEntity],
synchronize: true,
logging: true,
subscribers: [],
migrations: [],
cli: {
entitiesDir: "src/entities",
migrationsDir: "src/migrations",
subscribersDir: "src/subscribers"
}
}).then(connection => {
connection.getCustomRepository(ParentRepository);
connection.getCustomRepository(ChildRepository);
});
import { getCustomRepository } from "typeorm";
import { ParentRepository, ChildRepository } from "./repositories";
const parentRepository = getCustomRepository(ParentRepository);
const childRepository = getCustomRepository(ChildRepository);
const parent = new ParentEntity();
parent.name = "Parent";
parent.children = [];
const child1 = new ChildEntity();
child1.name = "Child 1";
child1.parent = parent;
const child2 = new ChildEntity();
child2.name = "Child 2";
child2.parent = parent;
parent.children.push(child1, child2);
parentRepository.saveWithChildren(parent);
这样,就可以在TypeORM中实现存根嵌套存储库了。通过使用TypeORM的Repository模式和Entity的关系,可以方便地进行嵌套存储库的操作。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云