【问题标题】:How to return all the subsections that belong to particular section?如何返回属于特定部分的所有小节?
【发布时间】:2021-02-23 21:49:50
【问题描述】:

我正在使用 Nestjs 作为我的后端,我正在尝试创建一个 api 调用来返回特定部分的所有小节,但不知道如何做到这一点,所以如果我能得到任何帮助或建议,我将不胜感激.

因此,如果我执行 Get/subsection/167(167 是部分 ID),那么我将获得该特定部分的所有小节。

实体

    @PrimaryGeneratedColumn({
        type: "int",
        name: "Id",
    })
    id: number;

    @Column("nvarchar", {
        nullable: false,
        unique: true,
        name: "Name"
    })
    name: string;

    @Column("nvarchar", {
        nullable: false,
        name: "ParentId"
    })
    parentId: number;

控制器

    @Get('/subsection/:parentId')
    async getHelpSubSection(@Req() req, @Param() params):Promise<HelpEntity[]>{
        return this.helpService.getHelpbySubSection(req.user, params.id);
    }

服务

  constructor(@InjectRepository(HelpEntity) private readonly helpRepo: Repository<HelpEntity>,

    async getHelpbySubSection(gmid: string, id: number) : Promise<any>{
        let check = await this.checkIfAdmin(gmid);
        if (!check) {
            throw new HttpException('Unauthorized', 401);
        } else {
            const res = await this.helpRepo.findOne()
            if (!res) {
                throw new NotFoundException(`This ID: ${id} is not found`)
            }
            return res;
        }
    }

在我的数据库中,我所有的父部分在 ParentId 中都有 NULL。

【问题讨论】:

    标签: angular typescript api backend nestjs


    【解决方案1】:

    您需要做的是编辑 findone 以查找您的条件:

     constructor(@InjectRepository(HelpEntity) private readonly helpRepo: Repository<HelpEntity>,
    
    async getHelpbySubSection(gmid: string, id: number) : Promise<any>{
        let check = await this.checkIfAdmin(gmid);
        if (!check) {
            throw new HttpException('Unauthorized', 401);
        } else {
            const res = await this.helpRepo.find({parentId : id})
            if (!res) {
                throw new NotFoundException(`This ID: ${id} is not found`)
            }
            return res;
        }
    }
    

    更新
    并在您的控制器中修复参数的名称

      @Get('/subsection/:parentId')
    async getHelpSubSection(@Req() req, @Param() params):Promise<HelpEntity[]>{
        return this.helpService.getHelpbySubSection(req.user, params.parentId);
    }
    

    更多详情请查看:find-options

    【讨论】:

    • 嗨 Youba,谢谢你,但是当我尝试它时,它只返回空数组。它不会返回特定部分的所有小节。有什么想法吗?
    • 尝试做 .find({ where: { parentId : id } });
    • 很遗憾我试过了,但我仍然只得到这个,[]。它没有返回任何不知道为什么的小节。
    • 你能验证什么'id'返回?
    • 勾选这个,把nvarchar改成int @Column("int", { nullable: false, name: "ParentId" }) parentId: number;
    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多