TypeORM:如何将In()与@ManyToMany关系一起使用



我有两个实体:SomethingOther(原型如下(。

如何使用In()方法通过OthersID数组查找所有具有相关OthersSomethings

我需要这样的东西:

const smths: Array<Something> = await connection.getRepository(Something).find({
others: In(arrayWithOthersIds),
});

实体:

@Entity()
class Something {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToMany(() => Other, (other) => other.smths, { cascade: true })
others: Other[];
}
@Entity()
class Other {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToMany(() => Something, (smth) => smth.others, { cascade: true })
smths: Something[];
}

您必须从多对多关系的一侧使用@JoinTable()。另外,我知道你不能在两边都使用{ cascade: true },所以去掉一个。并使用此查询:

const smths: Something[] = await connection
.getRepository(Something)
.createQueryBuilder('smth')
.innerJoin("smth.others", "others")
.where('others.id IN (:...ids)', { ids } ) // ids = [1, 2..]
.getMany();

最新更新