首页 > 解决方案 > 按左连接的最后一行过滤查询

问题描述

我有一个返回所有包裹的查询,它看起来像这样:

Parcel.createQueryBuilder('parcel')
  .leftJoinAndSelect('parcel.events', 'events')
  .orderBy({ 'events.timestamp': 'ASC' })
  .getMany()
  .then(parcels => this.res.send(parcels))
  .catch((err: Error) => this.res.status(500).send({ error: err.message }));

我正在尝试根据连接category中最后一行的列的值过滤结果events

的模型events如下所示:

@PrimaryGeneratedColumn()
id: number;

@Column()
category: string;

@Column()
title: string;

@Column({ nullable: true })
details?: string;

@Column()
location: string;

@Column({
  type: 'timestamp with time zone',
  default: () => 'CURRENT_TIMESTAMP',
})
timestamp: string;

@ManyToOne(() => Parcel)
parcel: Parcel;

我尝试了很多东西,但似乎都没有,我最后一次尝试是这样的:

Parcel.createQueryBuilder('parcel')
  .leftJoinAndSelect('parcel.events', 'events')
  .leftJoinAndSelect(qb => qb.subQuery()
    .select(['"parcelId"', 'category', 'timestamp'])
    .from(ParcelEvent, 'event')
    .orderBy({ timestamp: 'DESC' })
    .limit(1), 'lastEvent', '"lastEvent"."parcelId" = parcel.id')
  .orderBy({ 'events.timestamp': 'ASC' })
  .where('"lastEvent"."category" = :status', { status })
  .getMany()
  .then(parcels => this.res.send(parcels))
  .catch((err: Error) => this.res.status(404).send({ error: err.message }));

一般来说,我对 SQL 也有点陌生,所以这对我解决这个问题并没有太大帮助。

标签: node.jspostgresqltypeorm

解决方案


推荐阅读