如何从 OneToMany 关系中的值找到模型?
How can I find a model from a value in a OneToMany relationship?
我希望能够根据 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 相匹配的地方找到他们。
但是现在似乎正在发生的所有事情都是返回第一个用户,无论我给函数什么。
您需要将 QueryBuilder
与 join 一起使用:
await this.webUserRepository.createQueryBuilder('webUser')
.leftJoinAndSelect('webUser.profiles', 'profile')
.where ('profile.provider = :provider', { provider: '...' })
.andWhere('profile.platformID = :platformID', { platformID: '...' })
.getOne();
我希望能够根据 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 相匹配的地方找到他们。 但是现在似乎正在发生的所有事情都是返回第一个用户,无论我给函数什么。
您需要将 QueryBuilder
与 join 一起使用:
await this.webUserRepository.createQueryBuilder('webUser')
.leftJoinAndSelect('webUser.profiles', 'profile')
.where ('profile.provider = :provider', { provider: '...' })
.andWhere('profile.platformID = :platformID', { platformID: '...' })
.getOne();