我如何使用 TypeORM 的 QueryBuilder 编写此查询?
How do i write this query using TypeORM's QueryBuilder?
我直接在 mySQL 服务器上 运行 这段代码,我得到了想要的结果,现在我如何使用 typeORM 的 queryBuilder 在我的代码中复制它?
SELECT user.id, user.email, user.image, user.phone_number,
user.merchantLocationId, ugg.userGroupsId AS groupId, ug.description AS
groupName, ur.id as roleId, ur.description AS role_name, ugr.priviledges
FROM ipay.user, ipay.user_user_group_user_groups AS ugg,
ipay.user_group_roles AS ugr, ipay.user_groups AS ug,
ipay.user_roles AS ur
WHERE user.id = ugg.userId AND ugg.userGroupsId = ugr.group_id AND
ugr.role_id = ur.id AND user.email = "press@xyz.com";
将这种查询转换为 typeorm 有点困难。我能给出的最接近的例子是这样的
@Injectable()
export class UserService {
constructor(@InjectRepository(User) private readonly userRepository: Repository<User>) {}
async findUserByEmail(email: string): Promise<User | null> {
return await this.userRepository({
relations: ['roles', 'groups'],
where: {
email,
},
});
}
}
您的 UserEntity 看起来像这样
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({
unique: true,
})
email: string;
@ManyToMany(type => Group, group => group.users)
groups: Group[];
@ManyToOne(type => Role, role => role.users)
role: Role;
}
这不是完全匹配,但希望能让您深入了解如何实现查询。
我直接在 mySQL 服务器上 运行 这段代码,我得到了想要的结果,现在我如何使用 typeORM 的 queryBuilder 在我的代码中复制它?
SELECT user.id, user.email, user.image, user.phone_number,
user.merchantLocationId, ugg.userGroupsId AS groupId, ug.description AS
groupName, ur.id as roleId, ur.description AS role_name, ugr.priviledges
FROM ipay.user, ipay.user_user_group_user_groups AS ugg,
ipay.user_group_roles AS ugr, ipay.user_groups AS ug,
ipay.user_roles AS ur
WHERE user.id = ugg.userId AND ugg.userGroupsId = ugr.group_id AND
ugr.role_id = ur.id AND user.email = "press@xyz.com";
将这种查询转换为 typeorm 有点困难。我能给出的最接近的例子是这样的
@Injectable()
export class UserService {
constructor(@InjectRepository(User) private readonly userRepository: Repository<User>) {}
async findUserByEmail(email: string): Promise<User | null> {
return await this.userRepository({
relations: ['roles', 'groups'],
where: {
email,
},
});
}
}
您的 UserEntity 看起来像这样
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({
unique: true,
})
email: string;
@ManyToMany(type => Group, group => group.users)
groups: Group[];
@ManyToOne(type => Role, role => role.users)
role: Role;
}
这不是完全匹配,但希望能让您深入了解如何实现查询。