繁体   English   中英

如何通过manyToOne实际返回用户名而不是id? (类型)

[英]How to actually return the username instead of the id through manyToOne? (TYPEORM)

我有两个实体,其中一个是我的 User 实体和一个 Post 实体,在我的 Post 实体中我得到一个 ManyToOne 引用我的用户

发布实体

import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, OneToOne, PrimaryGeneratedColumn } from "typeorm";
import { User } from "./User";

@Entity('posts')
export class Post {
    @PrimaryGeneratedColumn('uuid')
    id: string;

    @ManyToOne(() => User)
    @JoinColumn()
    user: User

    @Column()
    title: string;

    @Column()
    desc: string;

    @CreateDateColumn({ 
        type: 'timestamp', 
        precision: 3
      })
      createdAt: Date;    
}

用户实体

import { BeforeInsert, BeforeUpdate, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
import bcrypt from 'bcryptjs';

@Entity('users')
export class User {
    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column()
    username: string;

    @Column()
    email: string;

    @Column()
    password: string;

    @Column({
        default: ''
    })
    tokenResetPass: string;


    @BeforeInsert()
    @BeforeUpdate()
    hashPassword() {
        this.password = bcrypt.hashSync(this.password, 8);
    }

}

这是有效的,每次我在用户中创建一个 Post 时,我都会发送我的用户的 Id,但问题是当我得到这个 Post 控制器时,我会收到 Id 格式的用户。 如何在 get 控制器的用户实体中提取“用户名”?

获得控制器职位

import { Request, Response } from "express";
import { AppDataSource } from "../../database/config";
import { Post } from "../../entities/Post";

class FindAllPostsController {
    async index(req: Request, res: Response) {

        try {
            const posts = await AppDataSource.manager.find(Post);

            return res.status(200).json(posts);
        } catch (err) {
            return res.status(500).json(err);
        }
    }
}

export default new FindAllPostsController();

我在邮递员那里得到的例子:

{
    "id": "27febc4a-1461-4146-a839-bb860a947de2",
    "title": "test 1",
    "desc": "testing a post",
    "createdAt": "2022-12-17T16:52:39.196Z"
}

我想收到什么:

{
    "id": "27febc4a-1461-4146-a839-bb860a947de2",
    "user": "username",
    "title": "test 1",
    "desc": "testing a post",
    "createdAt": "2022-12-17T16:52:39.196Z"
}

你需要加载你的关系。 在你的情况下 const post = await AppDataSource.manager.find(Post, {relations: "user"})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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