如何从OneToMany关系中的值中找到模型?

时间:2020-01-23 01:57:48

标签: typescript relationship typeorm

我希望能够基于OneToMany关系内部的值找到用户模型。

这是我的功能:

async getUserViaPlatform(provider: string, id: string) {
        return await this.webUserRepository.findOne({
            profiles: [{
                provider,
                platformID: id
            }]
        });
    }

用户模型为:

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

    @Column()
    name!: string;

    @Column({ nullable: true })
    picture?: string;

    @OneToMany(type => WebProfile, webProfile => webProfile.user, { eager: true })
    profiles!: WebProfile[];

    @CreateDateColumn()
    createdAt!: Date;

    @UpdateDateColumn()
    updatedAt!: Date;
}

“ WebProfile”是

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

    @Column()
    provider!: string;

    @Column()
    email!: string;

    @Column()
    platformID!: string;

    @ManyToOne(type => WebUser, user => user.profiles)
    user!: WebUser;

    @CreateDateColumn()
    createdAt!: Date;

    @UpdateDateColumn()
    updatedAt!: Date;
}

我希望找到一个用户的配置文件与提供者和ID相匹配的用户。 但是无论我提供什么功能,现在似乎正在发生的一切都是返回第一个用户。

1 个答案:

答案 0 :(得分:0)

您需要将QueryBuilderjoin一起使用:

await this.webUserRepository.createQueryBuilder('webUser')
    .leftJoinAndSelect('webUser.profiles', 'profile')
    .where   ('profile.provider   = :provider', { provider: '...' })
    .andWhere('profile.platformID = :platformID', { platformID: '...' })
    .getOne();