获取NestJs中httpRequest中的外键。

huangapple go评论66阅读模式
英文:

Get the foreign key in a httpRequest in nestJs

问题

我正在尝试在 NestJs 中发出许多请求,特别是使用我的用户角色进行一些请求,并且我希望能够列出所有符合 user.role = "Role's name" 的用户,但是我无法从我的 role 表中获取到外键 user。

我的控制器如下所示,我的两个实体相互引用,因为一个角色可以有一个或多个用户,而一个用户只能有一个角色。

控制器代码如下所示:

import { Controller, Get, Param, Post } from '@nestjs/common';
import { Body } from '@nestjs/common/decorators';
import { AuthDto } from 'src/authentification/auth.dto';
import { Role } from './role.entity';
import { User } from './user.entity';
import { UserService } from './user.service';

@Controller('user')
export class UserController {
    constructor(private readonly UserService: UserService){}

    @Get()
    async getAllUser(): Promise<User[]>{
        return this.UserService.getListUser();
    }

    @Get('/Role')
    async getListRole(): Promise<Role[]> {
        return this.UserService.getListRole();
    }

    // 其他方法省略...
}

这是服务的代码:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { AuthDto } from 'src/authentification/auth.dto';
import { Repository } from 'typeorm';
import { Role } from './role.entity';
import { User } from './user.entity';

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User) private usersRepository: Repository<User>,
        @InjectRepository(Role) private rolesRepository: Repository<Role>
    ){}

    // 其他方法省略...
}

用户实体:

import { Place } from "src/place/place.entity";
import { Science } from "src/science/science.entity";
import { TechnologieUser } from "src/technologie/technologieUser.entity";
import { Column, Entity, ManyToMany, ManyToOne, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { Role } from "./role.entity";

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: Number;

    @Column()
    pseudo: String;

    @Column()
    password: String;

    @Column()
    pointEffort: Number;

    @ManyToOne(type => Role, role => role.users)
    role: Role;

    // 其他属性省略...
}

角色实体:

import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { User } from "./user.entity";

@Entity()
export class Role {
    @PrimaryGeneratedColumn()
    id: Number;

    @Column()
    nom: String;

    @OneToMany(type => User, user => user.role)
    users: User[];
}

但是当我使用 getListRole() 方法时,我只得到了这个 获取NestJs中httpRequest中的外键。

所以,我没有在属性 role.users 中得到我的用户列表,这个属性是缺失的。因此,问题是:如何在 getListRole() 的数据中添加 role.users?非常感谢。

英文:

I'm trying to make many request in nestJs and specially some with the role of my users and i wanted to be able to list all users who match user.role = "Role's name" but i can't get the foreign key user from my table role.

My controller look like this and both of my entities reference each other as a role can have one or many user and a user one and only one role.

import { Controller, Get, Param, Post } from &#39;@nestjs/common&#39;;
import { Body } from &#39;@nestjs/common/decorators&#39;;
import { AuthDto } from &#39;src/authentification/auth.dto&#39;;
import { Role } from &#39;./role.entity&#39;;
import { User } from &#39;./user.entity&#39;;
import { UserService } from &#39;./user.service&#39;;

@Controller(&#39;user&#39;)
export class UserController {
    constructor(private readonly UserService: UserService){}

    @Get()
    async getAllUser(): Promise&lt;User[]&gt;{
        return this.UserService.getListUser();
    }

    @Get(&#39;/Role&#39;)
    async getListRole(): Promise&lt;Role[]&gt; {
        return this.UserService.getListRole();
    }

    @Get(&#39;/Role/:role&#39;)
    async getUserByRole(@Param(&#39;role&#39;) role : number): Promise&lt;User[]&gt; {
        return this.UserService.getUserByRole(+role);
    }

    @Get(&#39;/Pseudo/:pseudo&#39;)
    async getUserByPseudo(@Param(&#39;pseudo&#39;) pseudo : string): Promise&lt;User&gt; {
        return this.UserService.getUserByPseudo(pseudo);
    }

    @Get(&#39;/id/:id&#39;)
    async getUserById(@Param(&#39;id&#39;) id : number): Promise&lt;User&gt; {
        return this.UserService.getUserById(+id);
    }

    @Post(&#39;/New&#39;)
    async createUser(@Body() user: AuthDto){
        return this.UserService.createUser(user);
    }
}

and here is the service

import { Get, Injectable } from &#39;@nestjs/common&#39;;
import { InjectRepository } from &#39;@nestjs/typeorm&#39;;
import { AuthDto } from &#39;src/authentification/auth.dto&#39;;
import { Repository } from &#39;typeorm&#39;;
import { Role } from &#39;./role.entity&#39;;
import { User } from &#39;./user.entity&#39;;

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User) private usersRepository: Repository&lt;User&gt;,
        @InjectRepository(Role) private rolesRepository: Repository&lt;Role&gt;
    ){}

    getUserById(id): Promise&lt;User&gt; {
        return this.usersRepository.findOneOrFail(id);
    }

    getUserByPseudo(pseudo: string): Promise&lt;User&gt; {
        return this.usersRepository.findOne({pseudo});
    }

    getListRole(): Promise&lt;Role[]&gt; {
        return this.rolesRepository.find();
    }

    getListUser(): Promise&lt;User[]&gt; {
        return this.usersRepository.find();
    }

    getUserByRole(role): Promise&lt;User[]&gt; {
        return this.usersRepository.find({where: {role: role}});
    }

    createUser(data: AuthDto){
        const user = {
            pseudo: data.username,
            password: data.password,
            pointEffort: 10,
            scienceTab: [],
            inventaire: [],
            technologieTab: [],
            role: {
                id: 1,
                nom: &quot;joueur&quot;,
                users: []
            },
        };
        const result = this.usersRepository.save(user);
        return result;
    }
}

user.entity.ts

import { Place } from &quot;src/place/place.entity&quot;;
import { Science } from &quot;src/science/science.entity&quot;;
import { TechnologieUser } from &quot;src/technologie/technologieUser.entity&quot;;
import { Column, Entity, ManyToMany, ManyToOne, OneToMany, PrimaryGeneratedColumn } from &quot;typeorm&quot;;
import { Role } from &quot;./role.entity&quot;;

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: Number;

    @Column()
    pseudo: String;

    @Column()
    password: String;

    @Column()
    pointEffort: Number;

    @ManyToOne(type =&gt; Role, role =&gt; role.users)
    role: Role;

    @ManyToMany(type =&gt; Science, science =&gt; science.users)
    scienceTab: Science[];

    @OneToMany(type =&gt; TechnologieUser, technologieUser =&gt; technologieUser.user)
    technologieTab: TechnologieUser[];

    @OneToMany(type =&gt; Place, place =&gt; place.user)
    inventaire: Place[];
}

role.entity.ts

import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from &quot;typeorm&quot;;
import { User } from &quot;./user.entity&quot;;

@Entity()
export class Role {
    @PrimaryGeneratedColumn()
    id: Number;

    @Column()
    nom: String;

    @OneToMany(type =&gt; User, user =&gt; user.role)
    users: User[];
}

But when i use getListRole() i only get this 获取NestJs中httpRequest中的外键。

And so i don't have the list of my users returned in the property role.users which is missing.
So the question is : how can i have role.users added in the data of getListRole()?
Thx a lot

答案1

得分: 1

从参数中获取角色ID,然后执行以下操作:this.usersRepository.find({ relations: {Role: true}, where: { role: { id: roleId } } })

英文:

Get role id from params, then do, this.usersRepository.find({ relations: {Role: true}, where: { role: { id: roleId } } })

huangapple
  • 本文由 发表于 2023年2月19日 16:50:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定