TypeORM-左加入没有“deletedAtISNULL”
现在一直在搜索这个,不确定这在 SQL 世界中是否是非正统的东西,但我正在尝试做一个左连接,它计数不为空的“deletedAt”列,但我似乎无法找到一种方法来做一个左连接,其中包括删除。
这只是一个虚拟示例,说明了我正在尝试做什么,在这种情况下,我想检索此人的信息以及工作的信息,但工作已被软删除。
this.createQueryBuilder('person')
.leftJoinAndSelect('person.job', 'job')
由此产生的 SQL 查询在左连接上隐式添加了“IS NOT NULL”,但我有这种情况,我需要来自确实已删除的记录的信息。
我一直无法找到一种方法来包含它,就像您在根级别通过包含所做的那样。
.withDeleted();
任何人有任何提示?
回答
在我的测试中,TypeOrm 根据.withDeleted()是之前还是之后生成不同的查询.leftJoinAndSelect()
// Normal case: Exclude both soft-deleted 'Person' and 'Job':
this.createQueryBuilder("Person")
.leftJoinAndSelect('Person.job', 'Job');
// 'withDeleted() after the join: Include soft-deleted 'Person' BUT EXCLUDE soft-deleted 'Job':
this.createQueryBuilder("Person")
.leftJoinAndSelect('Person.job', 'Job')
.withDeleted();
// 'withDeleted() before the join: Include both soft-deleted 'Person' and 'Job':
this.createQueryBuilder("Person")
.withDeleted()
.leftJoinAndSelect('Person.job', 'Job');
因此,如果您想排除软删除的“人”但包括软删除的“工作”(我所期望的),则可以在加入之前使用 withDeleted(将包括所有内容)并添加您自己的条件然后排除软删除的“人”(即添加条件"Person.deletedAt IS NULL")。这样你就不需要做一个完整的 RAW 查询:
// 'withDeleted() before the join with extra condition: Exclude soft-deleted 'Person' BUT INCLUDE soft-deleted 'Job':
this.createQueryBuilder("Person")
.withDeleted()
.andWhere("Person.deletedAt Is Null")
.leftJoinAndSelect('Person.job', 'Job');
(我用 TypeORM 0.2.30 和 0.2.31 进行了测试并看到了相同的行为)。