播种:如何将创建的实体链接到另一个实体?

时间:2021-07-04 09:11:31

标签: javascript typescript typeorm

我使用 typeorm-seeding 为由 typeorm 处理的数据库设定种子。我有 2 个工厂用于 2 个实体 CustomerEvent

实体

// entity/Customer.ts
import { Entity, PrimaryGeneratedColumn, Column, OneToOne, ManyToMany, JoinTable, JoinColumn } from 'typeorm'
import { Event } from './Event'

@Entity()
export class Customer {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstname: string;

  @Column()
  lastname: string;

  @Column()
  email: string

  @ManyToMany(() => Event, event => event.customers, { cascade: true })
  @JoinTable()
  events: Promise<Event[]>
}


// entity/Event.ts
import { Entity, PrimaryColumn, Column, CreateDateColumn, OneToMany, ManyToMany, JoinTable, DeleteDateColumn } from 'typeorm'
import { Course } from './Course'
import { Customer } from './Customer'

@Entity()
export class Event {
  @PrimaryColumn()
  id: string;

  @Column()
  name: string;

  @ManyToMany(() => Customer, customer => customer.events)
  @JoinTable()
  customers: Promise<Customer[]>
}

工厂

// factory/event.ts
import { define, factory } from 'typeorm-seeding'

import { Event } from '../../entity/Event'

define(Event, (faker) => {
  const event = new Event()

  event.id = faker.company.bsBuzz()
  event.name = faker.company.catchPhraseNoun()
  event.date = faker.date.recent()

  return event
})


// factory/customer.ts
import { Customer } from '../../entity/Customer'

define(Customer, (faker) => {
  const customer = new Customer()

  customer.firstname = faker.name.firstName()
  customer.lastname = faker.name.lastName()
  customer.email = faker.internet.email()

  return customer
})

如您所见,一个 Customer 可以有多个 Event,不同的 Customer 可以参与同一个 Event。因此,我在播种部分的目标是创建 10 个不同的 Event,然后创建 100 个参与其中一些 CustomerEvent。所以我创建了 2 个种子文件:

// seed/create-events.ts
import { Factory, Seeder } from 'typeorm-seeding'
import { Event } from '../entity/Event'

export default class CreateEvents implements Seeder {
  public async run(factory: Factory): Promise<any> {
    await factory(Event)().createMany(10)
  }
}


// seed/create-customers.ts
import { Factory, Seeder } from 'typeorm-seeding'
import { Customer } from '../entity/Customer'

export default class CreateCustomers implements Seeder {
  // eslint-disable-next-line class-methods-use-this
  public async run(factory: Factory): Promise<any> {
    await factory(Customer)().createMany(100)
  }
}

然而,这只会创建一些条目,但不会将它们链接在一起。

我知道我可以在 Event 的工厂内使用 Customer 的工厂:

// factory/customer.ts
import { Customer } from '../../entity/Customer'

define(Customer, (faker) => {
  const customer = new Customer()

  customer.firstname = faker.name.firstName()
  customer.lastname = faker.name.lastName()
  customer.email = faker.internet.email()

  customer.events = factory(Event)().createMany(10)

  return customer
})

但这只会为每个 Event 创建 10 个不同的 Customer

那么如何将我的 Customer 链接到在 Event 命令期间创建的某些 seed:run 的种子?

0 个答案:

没有答案