TypeORM - 多对多关系,在连接的表上具有条件



我在podcasts表和episodes表之间有一个多对多关系。一个播客可以有多个分集,一个分集可以是多个播客的一部分。

@Entity({ name: 'podcasts' })
export class Podcast extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@ManyToMany(() => Episode, (episode) => episode.podcasts, { nullable: true })
@JoinTable({ name: 'podcast_episode_join' })
episodes: Episode[];
}
@Entity({ name: 'podcast_episodes' })
export class Episode extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column('boolean', { default: false })
is_published: boolean;
@ManyToMany(() => Podcast, (podcast) => podcast.episodes, { nullable: true, lazy: true })
podcasts: Podcast[];
}

我正在尝试获取一个播客(从其指定的 id 中)及其发布的所有剧集(is_published = true)。我下面的代码运行良好。

但是:在我的播客没有剧集的情况下,它不返回任何内容(undefined),而不是至少返回podcast对象(带有空的episodes属性)。我做错了什么?

const podcast = await this.podcastRepository
.createQueryBuilder('podcast')
.leftJoinAndSelect('podcast.episodes', 'episode')
.where('podcast.id = :id', { id })
.andWhere('episode.is_published = :isPub', { isPub: true })
.getOne();

我终于找到了如何获得它。仅当条件为真时,才会过滤结果:is_published = true。但是当播客中没有剧集时,is_publishednull.所以我们需要检查此属性是true还是NULL.

此外,我们必须确保在创建新行时永远不会NULLepisode表中的is_published列。它始终具有默认值(在本例中为:false)。

const podcast = await this.podcastRepository
.createQueryBuilder('podcast')
.leftJoinAndSelect('podcast.episodes', 'episode')
.where('podcast.id = :id', { id })
.andWhere(
new Brackets((qb) => {
qb
// if episode is published
.where('episode.is_published = :isPub', { isPub: true })
// if there is no episode
.orWhere('episode.is_published IS NULL', { isPub: true });
}),
)
.getOne();