【问题标题】:TypeORM, ManyToOne relation: get parents rows that have no child relationsTypeORM,ManyToOne 关系:获取没有子关系的父行
【发布时间】:2021-02-10 08:45:04
【问题描述】:

我有 2 张桌子,listsitems。一个列表可以有 0 个或多个项目。一个项目只在一个列表中。

export class List {
  @OneToMany(() => Item, (item) => item.list, {
    nullable: true,
  })
  items: Item[];
}

export class Item {
  @ManyToOne(() => List, (list) => list.items)
  list: List;
}
  • 如何获得所有具有0项的list对象?

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

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

【问题讨论】:

    标签: mysql typeorm


    【解决方案1】:

    您的错误原因是您在查询中仅选择了“list”,而没有包含“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 Query Logging 以查看生成的 SQL 并正确获取这些 SQL,尤其是在您的数据库区分大小写的情况下)。

    【讨论】:

    • 非常感谢您的帮助。它现在完美运行,我学到了一些新东西!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    相关资源
    最近更新 更多