Skip to content

Commit 83f29cd

Browse files
Merge branch 'Sikora00-docs/typeorm'
2 parents 55d61a3 + 3cac4ba commit 83f29cd

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

content/techniques/sql.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,63 @@ With that option specified, every entity registered through the `forFeature()` m
358358

359359
> warning **Warning** Note that entities that aren't registered through the `forFeature()` method, but are only referenced from the entity (via a relationship), won't be included by way of the `autoLoadEntities` setting.
360360
361+
#### Separating entity definition
362+
363+
You can define an entity and its columns right in the model, using decorators. But some people prefer to define entities and their columns inside separate files using the ["entity schemas"](https://typeorm.io/#/separating-entity-definition).
364+
365+
```typescript
366+
import { EntitySchema } from 'typeorm';
367+
import { User } from './user.entity';
368+
369+
export const UserSchema = new EntitySchema<User>({
370+
name: 'User',
371+
target: User,
372+
columns: {
373+
id: {
374+
type: Number,
375+
primary: true,
376+
generated: true,
377+
},
378+
firstName: {
379+
type: String,
380+
},
381+
lastName: {
382+
type: String,
383+
},
384+
isActive: {
385+
type: Boolean,
386+
default: true,
387+
},
388+
},
389+
relations: {
390+
photos: {
391+
type: 'one-to-many',
392+
target: 'Photo', // the name of the PhotoSchema
393+
},
394+
},
395+
});
396+
```
397+
398+
> warning error **Warning** If you provide the `target` option, the `name` option value has to be the same as the name of the target class.
399+
> If you do not provide the `target` you can use any name.
400+
401+
Nest allows you to use an `EntitySchema` instance wherever an `Entity` is expected, for example:
402+
403+
```typescript
404+
import { Module } from '@nestjs/common';
405+
import { TypeOrmModule } from '@nestjs/typeorm';
406+
import { UserSchema } from './user.schema';
407+
import { UsersController } from './users.controller';
408+
import { UsersService } from './users.service';
409+
410+
@Module({
411+
imports: [TypeOrmModule.forFeature([UserSchema])],
412+
providers: [UsersService],
413+
controllers: [UsersController],
414+
})
415+
export class UsersModule {}
416+
```
417+
361418
#### Transactions
362419

363420
A database transaction symbolizes a unit of work performed within a database management system against a database, and treated in a coherent and reliable way independent of other transactions. A transaction generally represents any change in a database ([learn more](https://en.wikipedia.org/wiki/Database_transaction)).

0 commit comments

Comments
 (0)