@@ -142,7 +142,8 @@ All script are defined in the package.json file, but the most important ones are
142
142
143
143
### Database Migration
144
144
145
- - Run ` ./node_modules/.bin/typeorm create -n <migration-file-name> ` to create a new migration file.
145
+ - Run ` typeorm migrations:create -n <migration-file-name> ` to create a new migration file.
146
+ - Try ` typeorm -h ` to see more useful cli commands like generating migration out of your models.
146
147
- To migrate your database run ` npm start db.migrate ` .
147
148
- To revert your latest migration run ` npm start db.revert ` .
148
149
- Drops the complete database schema ` npm start db.drop ` .
@@ -267,19 +268,44 @@ factory.define(User, (faker: typeof Faker) => {
267
268
});
268
269
` ` `
269
270
270
- This is a nested example for a factory to get the foreign key of the other entity .
271
+ This can be used to pass some dynamic value into the factory .
271
272
272
273
` ` ` typescript
273
274
factory .define (Pet , (faker : typeof Faker , args : any []) => {
274
275
const type = args [0 ];
275
276
return {
276
277
name: faker .name .firstName (),
277
- type: type || ' dog' ,
278
- userId: factory .get (User ).returning (' id' )
278
+ type: type || ' dog'
279
279
};
280
280
});
281
281
` ` `
282
282
283
+ To deal with relations you can use the entity manager like this.
284
+
285
+ ` ` ` typescript
286
+ import { SeedsInterface , FactoryInterface , times } from ' ../../lib/seeds' ;
287
+ import { Pet } from ' ../../../src/api/models/Pet' ;
288
+ import { User } from ' ../../../src/api/models/User' ;
289
+
290
+ export class CreatePets implements SeedsInterface {
291
+
292
+ public async seed(factory : FactoryInterface ): Promise <any > {
293
+ const connection = await factory .getConnection ();
294
+ const em = connection .createEntityManager ();
295
+
296
+ await times (10 , async (n ) => {
297
+ // This creates a pet in the database
298
+ const pet = await factory .get (Pet ).create ();
299
+ // This only returns a entity with fake data
300
+ const user = await factory .get (User ).make ();
301
+ user .pets = [pet ];
302
+ await em .save (user );
303
+ });
304
+ }
305
+
306
+ }
307
+ ` ` `
308
+
283
309
### 2. Create a seed file
284
310
285
311
The seeds files define how much and how the data are connected with each other. The files will be executed alphabetically.
0 commit comments