Skip to content

Commit 181eb01

Browse files
Merge branch 'docs/typeorm' of https://github.com/Sikora00/docs.nestjs.com into Sikora00-docs/typeorm
2 parents 55d61a3 + beda3c8 commit 181eb01

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

content/techniques/sql.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,64 @@ 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 an entity and its columns inside separate files which are called ["entity schemas"](https://typeorm.io/#/separating-entity-definition).
364+
365+
366+
```typescript
367+
import { EntitySchema } from 'typeorm';
368+
import { User } from './user.entity';
369+
370+
export const UserSchema = new EntitySchema<User>({
371+
name: 'User',
372+
target: User,
373+
columns: {
374+
id: {
375+
type: Number,
376+
primary: true,
377+
generated: true
378+
},
379+
firstName: {
380+
type: String
381+
},
382+
lastName: {
383+
type: String
384+
},
385+
isActive: {
386+
type: Boolean,
387+
default: true
388+
}
389+
},
390+
relations: {
391+
photos: {
392+
type: 'one-to-many',
393+
target: 'Photo' // The name of the PhotoSchema
394+
}
395+
}
396+
});
397+
```
398+
> 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+
402+
Nest allows you to use an `EntitySchema` instance wherever an `Entity` is expected, for example:
403+
404+
```typescript
405+
import { Module } from '@nestjs/common';
406+
import { TypeOrmModule } from '@nestjs/typeorm';
407+
import { UserSchema } from './user.schema';
408+
import { UsersController } from './users.controller';
409+
import { UsersService } from './users.service';
410+
411+
@Module({
412+
imports: [TypeOrmModule.forFeature([UserSchema])],
413+
providers: [UsersService],
414+
controllers: [UsersController],
415+
})
416+
export class UsersModule {}
417+
```
418+
361419
#### Transactions
362420

363421
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)