首页 文章

如何使用返回多个项目的TypeORM设置Nestjs查询?

提问于
浏览
0

我从Angular发送此URL:

http://localhost:3000/api/skills?category_id=2

问题是,如何修复我的代码,以便检索category_id为2的所有技能?

我不是在寻找技巧,我可以毫无问题地获取个人技能 . 记录看起来像这样:

skill_id
skill_name
category_id

在skill.controller我有这个 . 我一直在试验@Get param,但仍然无法调用此函数 . 从不调用Console.log . 此外,我不知道如何告诉服务我想要所有技术记录,其category_id为2或需要任何数量 .

@Get('?category_id')
  public async getSkillsByCategory(@Param('category_id') categoryId) {
    console.log('skills recordId in controller: ', categoryId.id);
    return this.skillsService.getSkillsByCategory(categoryId.id);
  }

在skills.service我有这个,但它没有告诉db,Postgres,查询category_id 2.不知怎的,这需要发生,但category_id列似乎不是一个常规的参数 .

async getSkillsByCategory(categoryId) {
    console.log('categoryId in service', categoryId);
    return await this.skillsRepository.find(categoryId);
  }

1 回答

  • 1

    假设您的技能根路径为 http://localhost:3000/api/skills/ ,请将您的控制器更改为:

    import { ParseIntPipe } from '@nestjs/common';
      // you can use ParseIntPipe to validate if id is actually number, very useful
    
      @Get('category/:id')  //  or  @Get('/category/:id')
      public async getSkillsByCategory(@Param('id', new ParseIntPipe()) id) {
        return this.skillsService.getSkillsByCategory(id);
      }
    

    而且你的服务:

    async getSkillsByCategory(id) {
      return await this.skillsRepository.find({ category_id: id });
    }
    

    现在拨打 http://localhost:3000/api/skills/category/2 .

相关问题