Seeding - how to add FK to the factory? #232
Unanswered
eliezerbaschkier
asked this question in
Q&A
Replies: 1 comment 1 reply
-
You can do this: Method 1factoryManager.set(States, (faker: Faker, meta: unknown) => {
const state = new States()
state.country = 99 // HERE!
return state
})
const stateFactory = await factoryManager.get(States)
await stateFactory.save() Method 2// states.seeder.ts
import { DataSource } from 'typeorm'
import { Seeder, SeederFactoryManager } from 'typeorm-extension'
import { States } from 'path/to/entities'
export default class ServiceSeeder implements Seeder {
public async run(
dataSource: DataSource,
factoryManager: SeederFactoryManager,
): Promise<void> {
const stateFactory = await factoryManager.get(States)
stateFactory.setMeta(1) // Here you can pass data to factory
await stateFactory.saveMany(60)
}
} // state.factory.ts
import { setSeederFactory } from 'typeorm-extension'
import { State } from 'path/to/entity'
export default setSeederFactory(
State,
(faker, meta: number) => {
const state = new States();
state.descri = faker.address.state();
state.country = meta; // HERE you can get the values passed by seeder to factory
return state;
},
) |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi Peter!
Thank you very much for supporting this library!
Quick question: I have two entities,
Countries
andStates
, whereCountry
is a FK ofStates
.How do I specify in
States.Factory.ts
thatstates.country
should take one of the rows generated inCountries.Factory.ts
?I leave below my code.
Thanks for the help!
Beta Was this translation helpful? Give feedback.
All reactions