按左联接的最后一行过滤查询

时间:2020-05-21 16:04:37

标签: node.js postgresql typeorm

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

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也有点陌生,因此对解决这个问题并没有太大帮助。

0 个答案:

没有答案