使用typeorm-seeding填充数据时如何关联已创建的两个实体?
解决方法
你可以通过以下步骤实现关联已创建的Event数据:
1. 修正多对多注解配置
首先修复实体中的错误配置:多对多关联仅需在关联拥有方添加@JoinTable注解,你当前两个实体都加了该注解会导致生成两张独立的中间表,无法正确建立关联。删除Event实体中的@JoinTable即可:
// entity/Event.ts 修正后 @ManyToMany(() => Customer, customer => customer.events) // 删除原有的 @JoinTable() 注解 customers: Promise<Customer[]>
2. 调整种子执行顺序
在TypeORM配置文件(通常为ormconfig.json或data-source.ts)中调整种子文件的加载顺序,确保先执行Event的创建逻辑:
// ormconfig.json 示例 { // 其他配置项保持不变 "seeds": [ "src/seed/create-events.ts", "src/seed/create-customers.ts" ] }
3. 修改Customer种子文件,绑定已有Event
Seeder的run方法第二个参数可以拿到当前数据库连接实例,我们可以先查询所有已创建的Event,再给每个生成的Customer随机绑定部分Event:
// seed/create-customers.ts 修正后 import { Factory, Seeder } from 'typeorm-seeding' import { Connection } from 'typeorm' import { Customer } from '../entity/Customer' import { Event } from '../entity/Event' export default class CreateCustomers implements Seeder { public async run(factory: Factory, connection: Connection): Promise<any> { // 查询所有已创建完成的Event const allEvents = await connection.getRepository(Event).find() await factory(Customer)() // 每个Customer实例生成后执行关联逻辑 .map(async (customer) => { // 随机取2-5个Event绑定,可按需调整数量范围 const relatedEvents = allEvents .sort(() => 0.5 - Math.random()) .slice(0, Math.floor(Math.random() * 4) + 2) customer.events = Promise.resolve(relatedEvents) return customer }) .createMany(100) } }
原理说明
你之前的实现会重复生成Event,是因为在工厂中调用factory(Event)().createMany()时每次都会插入新的Event数据。上述方案先读取已经存在的Event实例,再直接赋值给关联属性,不会生成新的Event数据,符合你的需求。
内容的提问来源于stack exchange,提问作者johannchopin
相关产品推荐
相关产品推荐

