mysql - TypeORM,ManyToOne 关系:获取没有子关系的父行
问题描述
我有 2 张桌子,lists
并且items
. 一个列表可以有 0 个或多个项目。一个项目仅在一个列表中。
export class List {
@OneToMany(() => Item, (item) => item.list, {
nullable: true,
})
items: Item[];
}
export class Item {
@ManyToOne(() => List, (list) => list.items)
list: List;
}
- 如何获取所有
list
具有0项的对象?
我下面的代码返回错误:“where 子句”中的未知列“list.items”。
const listsWithoutItems = await this.listsRepository
.createQueryBuilder('list')
.where('list.item IS NULL')
.getMany();
解决方案
错误的原因是您在查询中仅选择了“列表”,而没有包含“list.items”。
您可以只获取没有“项目”的“列表”记录的一种方法是将其专门添加到.where
const listsWithoutItems = await this.listsRepository
.createQueryBuilder('list')
.where('NOT EXISTS (SELECT * FROM Item i WHERE i.listId = list.id)')
.getMany();
另一种方法是从 'list' 到 'item' 进行左连接,仅选择具有 NULL 'Item.Id' 的那些
const listsWithoutItems = await listsRepository
.createQueryBuilder('list')
.leftJoin('list.items', 'Item')
.where('Item.id IS NULL')
.getMany();
(您可能需要打开TypeOrm 查询日志以查看生成的 SQL 并正确获取这些 SQL,尤其是在您的数据库区分大小写的情况下)。
推荐阅读
- solaris - Solaris 11:安装 Solaris 开发者工作室:错误
- linux - 文件的链接
- amazon-web-services - AWS CodePipeline 仅部署自上次部署以来已更改的文件,而不是简单地替换应用程序
- apache-spark - Spark 中的重新分区 - SQL API
- javascript - 数组的正确使用
- python - 无法在单独的输出文件中使用 for 循环将数据保存在不同的行中
- assembly - 奇怪的 jmp 与调用行为
- javascript - 为什么这个 dropzone.js 不能上传到实时服务器?
- c++ - 如何使用 gnuplot 为箭头设置动画?
- python - 如何创建一个数字增加 3 的数组?