简体   繁体   中英

How do I return only the required nested field in NestJs?

I'm trying to get one record from a nested table.

controller:

@Get(':id/type')
  async getType(): Promise<User[]> {
      return this.userService.findType();
  };

service:

async findType(id: FindOptionsWhere<number>): Promise<User[]> {
return this.userRepository.find({
  select: [""], //here I want to select type.type_name
  where: {user_id: id}
    });
  }

entity:

@Entity({ name: 'user' })
export class User {
    
          @PrimaryGeneratedColumn()
          public user_id: number;
        
          @OneToOne(() => Type)
          @JoinColumn({ name: "type_id", referencedColumnName: "type_id" })
          public type: Type;
    
          @Column({ nullable: true, name: 'test_id', type: 'int' })
          public test_id: number;

table user: user_id|type_id|test_id

table type: type_id|type_name|type_adr

How can I retrieve only type.type_name in the url /:id/type? thanks

First you have to fix some details, like the param in your route (id). So using your ex.

I'll going to modify the order of the route by convention.

// Controller

@Get('type/:id')
  async getType(@Param('id') id: string): Promise<User[]> {
      return this.userService.findType();
  };

// Service

async findType(id: string): Promise<User[]> {
return this.userRepository.find({
    select: { type: true },
    where: { user_id: id }
  });
}

// And using QueryBuilder

findType(id: string) {
    return this.createQueryBuilder('user')
         .select(['user.type'])
         .where('user.user_id = :id', { id })
         .getMany(); // or .getRawMany() to get the raw type
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM