npm 我应该如何编写typeorm实体并查找代码?

k2fxgqgv  于 2023-03-30  发布在  其他
关注(0)|答案(2)|浏览(132)

我创建了两个表,一个是用户表,另一个是朋友表,其中包含用户之间的关系。
创建好友表是为了解决用户之间的多对多关系。
如何创建typeorm实体并检索下面表单中的数据?

{
    "id": "1000014",
    "name": "fu",
    "address": aasd,
    "createdTime": "2023-03-09T01:00:00.000Z",
    "updatedTime": "2023-03-09T09:11:18.243Z",
    "friends": [
      {
        "id": "5",
        "name": "kaka",
        "address": asdf,
        "createdTime": "2023-03-09T01:00:00.000Z",
        "updatedTime": "2023-03-09T09:11:18.243Z"
      },
      {
        "id": "6",
        "name": "lod",
        "address": asdf,
        "createdTime": "2023-03-09T01:00:00.000Z",
        "updatedTime": "2023-03-09T09:11:18.243Z"
      },
      {
        "id": "7",
        "name": "asdf",
        "address": asdf,
        "createdTime": "2023-03-09T01:00:00.000Z",
        "updatedTime": "2023-03-09T09:11:18.243Z"
      },
      {
        "id": "8",
        "name": "qwer",
        "address": asdf,
        "createdTime": "2023-03-09T01:00:00.000Z",
        "updatedTime": "2023-03-09T09:11:18.243Z"
      },
      {
        "id": "9",
 
        "name": "qwer",
        "address": dasfsdf,
        "createdTime": "2023-03-09T01:00:00.000Z",
        "updatedTime": "2023-03-09T09:11:18.243Z"
      }
    ]
  },
  {
    "id": "1000120",
    "name": "asdvv",
    "address": asdf,
    "createdTime": "2023-03-08T15:00:00.000Z",
    "updatedTime": "2023-03-09T09:11:18.243Z",
    "friends": [
      {
iibxawm4

iibxawm41#

假设您已经在数据库中创建了必要的表,您可以在TypeORM中为User和Friend表创建两个实体。
用户实体:

import { Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable } from 'typeorm';
import { Friend } from './friend.entity';

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

  @Column()
  name: string;

  @Column()
  address: string;

  @Column()
  createdTime: Date;

  @Column()
  updatedTime: Date;

  @ManyToMany(() => Friend)
  @JoinTable({
    name: 'user_friend',
    joinColumn: { name: 'user_id', referencedColumnName: 'id' },
    inverseJoinColumn: { name: 'friend_id', referencedColumnName: 'id' },
  })
  friends: Friend[];
}

好友实体:

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class Friend {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  address: string;

  @Column()
  createdTime: Date;

  @Column()
  updatedTime: Date;
}

创建实体后,您可以使用TypeORM以所需格式检索数据,使用如下查询:

import { getRepository } from 'typeorm';
import { User } from './entities/user.entity';

async function getUsersWithFriends(): Promise<User[]> {
  const userRepository = getRepository(User);
  const users = await userRepository.find({ relations: ['friends'] });
  return users;
}
pxy2qtax

pxy2qtax2#

这可能行得通:

const data = await userRepository.find({
  relations: {
    friends: true
  }
});

相关问题