英文:
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() 方法时,我只得到了这个 。
所以,我没有在属性 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 '@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();
}
@Get('/Role/:role')
async getUserByRole(@Param('role') role : number): Promise<User[]> {
return this.UserService.getUserByRole(+role);
}
@Get('/Pseudo/:pseudo')
async getUserByPseudo(@Param('pseudo') pseudo : string): Promise<User> {
return this.UserService.getUserByPseudo(pseudo);
}
@Get('/id/:id')
async getUserById(@Param('id') id : number): Promise<User> {
return this.UserService.getUserById(+id);
}
@Post('/New')
async createUser(@Body() user: AuthDto){
return this.UserService.createUser(user);
}
}
and here is the service
import { Get, 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>
){}
getUserById(id): Promise<User> {
return this.usersRepository.findOneOrFail(id);
}
getUserByPseudo(pseudo: string): Promise<User> {
return this.usersRepository.findOne({pseudo});
}
getListRole(): Promise<Role[]> {
return this.rolesRepository.find();
}
getListUser(): Promise<User[]> {
return this.usersRepository.find();
}
getUserByRole(role): Promise<User[]> {
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: "joueur",
users: []
},
};
const result = this.usersRepository.save(user);
return result;
}
}
user.entity.ts
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;
@ManyToMany(type => Science, science => science.users)
scienceTab: Science[];
@OneToMany(type => TechnologieUser, technologieUser => technologieUser.user)
technologieTab: TechnologieUser[];
@OneToMany(type => Place, place => place.user)
inventaire: Place[];
}
role.entity.ts
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[];
}
But when i use getListRole() i only get this
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 } } })
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论