簡體   English   中英

NestJS 中的 TypeORM - 如何在實體中獲取 MySQL 嵌套對象並對子關系進行“where”查詢?

[英]TypeORM in NestJS - how to get MySQL nested object like in the entity and do a 'where' query on subrelation?

我嘗試將其作為 QueryBuilder 執行此操作:

const ret = await getManager()
  .createQueryBuilder(Order, 'o')
  .leftJoinAndSelect(PartOfOrder, 'p', 'o.id = p.orderId')
  .where(':purcharser = o.purchaserId', { purcharser: purcharserId })
  .andWhere(':supplier = p.supplierId', { supplier: supplier.id })
  .andWhere('p.status = 0')
  .getRawMany();

並有如下結果:

{
    "o_id": "3454d7fe-072a-4983-a811-5ce45106488c",
    "o_date": "2021-09-01T07:30:07.000Z",
    "o_amount": 20598,
    "o_paymentId": "b8c937f0-4d61-4f84-8760-ebb0ec5bc35f",
    "o_purchaserId": "5adeb8ed-6703-4e82-a7e3-2b10d8fbf912",
    "p_id": "8c6bfc56-aa7a-4d9a-a872-7ccd370a7137",
    "p_amount": 200,
    "p_delivery": 0,
    "p_message": "",
    "p_date": "2021-09-01T07:30:07.000Z",
    "p_status": 0,
    "p_pickupCode": 8073,
    "p_supplierId": "e41aff94-343c-4062-b55a-90bf1b3e3695",
    "p_orderId": "3454d7fe-072a-4983-a811-5ce45106488c"
}

在這里,我有平坦的響應,我需要從 SQL 嵌套。

下面我有一個find()查詢,我不知道把嵌套對象的位置放在where

const ret = await Order.find({
  relations: ['partsOfOrder', 'partsOfOrder.products'],
  where: { purchaser: purcharserId },
});

編輯

我的訂單實體關系道具:

@OneToMany(
  type => PartOfOrder,
  entity => entity.order,
  {
    cascade: true,
    onDelete: 'CASCADE',
  },
)
@JoinColumn()
partsOfOrder: IPartOfOrder[];

我可以在任何循環中過濾它,但服務器會死,並且真的需要在 SQL 中執行此操作

在您的第一個解決方案中,嘗試使用getMany()而不是getRawMany() ,您將獲得一個嵌套對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM