I want to be able to find a user model based off a value inside of a OneToMany relationship.
Here is my function:
async getUserViaPlatform(provider: string, id: string) {
return await this.webUserRepository.findOne({
profiles: [{
provider,
platformID: id
}]
});
}
The User model is:
@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;
}
And "WebProfile" is
@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;
}
I want a user to be found where they have a profile which matches the provider and id. But all that seems to be happening right now is returning the first user no matter what i give to the function.
You need to use QueryBuilder
with a join:
await this.webUserRepository.createQueryBuilder('webUser')
.leftJoinAndSelect('webUser.profiles', 'profile')
.where ('profile.provider = :provider', { provider: '...' })
.andWhere('profile.platformID = :platformID', { platformID: '...' })
.getOne();