首页 > 解决方案 > TypeORM - 使用 TypeORM 存储库查询 OneToMany 相关实体

问题描述

我只是想查询一个 OneToMany 相关实体,但是在这个查询中,我需要通过 Entity1 中的查询从 Entity2 获取预先加载的数据。

例子:

我有这些实体:

//Entity1

@Entity('roles')
export class Role {
    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column()
    title: string;

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


//Entity2

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

    @Column()
    name: string;

    @Column('uuid')
    role_id: string;

    @ManyToOne(() => Role, role => role.users)
    @JoinColumn({ name: 'role_id' })
    role: Role;
}

所以,我试图做这样的查询:

const rolesRepository = getRepository(Role);

rolesRepository.find({
  where: {
    // user's name
    name: ILike("%john%")
  },
  relations: ['users']
});

我需要使用用户名来查找名称包含“John”的用户的所有角色,并获取角色和用户数据(急切加载),例如:

Role: {
  id: '6fa6fa8b-f0e1-48bf-b0ec-61eb35585eba',
  title: 'Pathfinder',
  users: [
    {
      id: 'c9097d7d-b83b-412b-9c81-6a918c07e360',
      name: 'John Doe',
      role_id: '6fa6fa8b-f0e1-48bf-b0ec-61eb35585eba'
    },
    {
      id: 'ed1fffb0-dae5-46ce-83ce-38b379483c7f',
      name: 'Johnny',
      role_id: '6fa6fa8b-f0e1-48bf-b0ec-61eb35585eba'
    }
  ]
}

我不想{ eager: true }在实体中使用,因为我只需要一个使用急切加载的查询(在实体中使用我会过度获取)。

这不起作用,我知道以这种方式进行查询是没有意义的。我这样做只是为了理解目的。

数据库:Postgres

标签: postgresqlrelationshipone-to-manytypeorm

解决方案


推荐阅读