首页 > 解决方案 > 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;
}

我下面的代码返回错误:“where 子句”中的未知列“list.items”。

const listsWithoutItems = await this.listsRepository
  .createQueryBuilder('list')
  .where('list.item IS NULL')
  .getMany();

标签: mysqltypeorm

解决方案


错误的原因是您在查询中仅选择了“列表”,而没有包含“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,尤其是在您的数据库区分大小写的情况下)。


推荐阅读