首页 > 解决方案 > 在 Postgres 中返回不受影响的行

问题描述

我有一个 Postgres 数据库并使用ObjectionJS作为我的 ORM。

我有以下 ObjectionJS 代码来修补表的两列user_system

  public static async DeleteSystem(systemId: number, context: Context): Promise<UserSystem> {
    const system = await UserSystem.query().context(context).patch({
      state: PointInTimeState.inactive,
      receiveNotifications: false
    }).where({
      system_id: systemId
    }).throwIfNotFound().debug()
    //("as any" for now because the system variable is a number at this point (i.e NOT of type Promise<UserSystem> as in the signature)
    return system as any 
  }

问题

  1. 有没有办法可以返回所有不受此补丁影响的行?
  2. 如果是这样,如何不必向后端编写两个单独的查询(更新然后重新查询新数据)?

标签: postgresqlobjection.js

解决方案


据我所知,编写 CTE 将两个查询组合为单个查询是唯一的方法。

有异议/ knex 他们可以用https://knexjs.org/#Builder-with

因此,在查询中,您执行.patch(...).where(...).returning('id')并在主查询中选择表中的所有行,这些行不在第一个查询返回的 id 集中。

像这样的东西(不确定这是否像这样有异议):

UserSystem.query().context(context).with('patchedIds', 
    UserSystem.query().patch({
      state: PointInTimeState.inactive,
      receiveNotifications: false
    }).where({
      system_id: systemId
    }).returning('id') 
  ).whereNotIn('id', builder => {
    builder.from('patchedId').select('id')
  })

推荐阅读