Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example Model with Relations and DTO #14

Closed
pietrzakadrian opened this issue Dec 13, 2019 · 0 comments
Closed

Example Model with Relations and DTO #14

pietrzakadrian opened this issue Dec 13, 2019 · 0 comments

Comments

@pietrzakadrian
Copy link

I am trying to create a model with a relation with DTO and call the list of users with these relations.

Model User:

...
@Column()
    firstName: string;

@OneToOne(
        type => UserSalaryEntity,
        userSalary => userSalary.user,
        {
            nullable: false,
        },
    )
    userSalary: UserSalaryEntity;
...

User DTO:

export class UserDto extends AbstractDto {
    @ApiProperty()
    firstName: string;

    @ApiProperty({ type: UserSalaryDto })
    userSalary: UserSalaryDto;

    constructor(
        user: UserEntity,
        userSalary: UserSalaryDto,
    ) {
        super(user);
        this.firstName = user.firstName;
        this.userSalary = relations.userSalary;
    }
}

Model UserSalary:

...
@Column('decimal', { precision: 13, scale: 2, default: 0 })
    salary: number;

@OneToOne(
        type => UserEntity,
        user => user.userSalary,
        { nullable: false },
    )
    @JoinColumn({ name: 'user_id' })
    user: UserEntity;
...

UserSalary DTO:

export class UserSalaryDto extends AbstractDto {
    @ApiProperty()
    salary: number;

    @ApiProperty()
    userId: number;

    constructor(userSalary: UserSalaryEntity, user: UserDto) {
        super(userSalary);
        this.salary = userSalary.salary;
        this.userId = user.id;
    }
}

I'm not sure if my dto looks good, that's what I thought.
But now I'm trying to do endpoint GET /users:

async getUsers(
        pageOptionsDto: UsersPageOptionsDto,
    ): Promise<UsersPageDto> {
        const queryBuilder = this.userRepository.createQueryBuilder('user');
        const [users, usersCount] = await queryBuilder
            .leftJoinAndSelect('user.userSalary', 'userSalary')
            .skip(pageOptionsDto.skip)
            .take(pageOptionsDto.take)
            .getManyAndCount();

        const pageMetaDto = new PageMetaDto({
            pageOptionsDto,
            itemCount: usersCount,
        });

        return new UsersPageDto(users.toDtos(), pageMetaDto);
    }

there is a problem with dto.
Could you create an example entity for me according to this boilerplate with relations?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant