TypeORM,ManyToOne关系:获取没有子关系的父母行

艾蒂安

我有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;
}
  • 如何获取所有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();

另一种方法是从“列表”到“项目”进行左联接,仅选择具有“ Item.Id”为NULL的那些

const listsWithoutItems = await listsRepository
    .createQueryBuilder('list')
    .leftJoin('list.items', 'Item')
    .where('Item.id IS NULL')
    .getMany();

(您可能需要打开TypeOrm查询日志以查看生成的SQL并完全正确地使用它们,尤其是在您的数据库区分大小写的情况下)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章