postgresql - 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
解决方案
推荐阅读
- internet-explorer - centos 7无法安装IE
- node.js - 尝试使用 Google 官方库从 Node.js 接收 Gmail 时出错
- c - 如何声明可变长度数组并将其初始化为零?
- ios - SwiftUI Text 似乎依赖于 Image
- jenkins - 为什么詹金斯“配置系统”中“添加 GitHub 服务器”下的“添加凭据”不起作用?
- c# - 在没有 IIS 的情况下部署捆绑包
- php - PHP转换器参数如何从数组中返回单个值
- python - Geopandas:如何在 geoandas 数据框之间进行空间连接?
- java - 有效的审计方式
- tensorflow - 如何将 TensorFlow model.json 转换为 model.pb 文件