如何在异议模型的 $afterUpdate 挂钩中获取整个更新条目?

How can I get the entire updated entry in a $afterUpdate hook in objection models?

我使用 Objection.js 作为简单降雨应用程序的 ORM。当较低级别 table 的整体已更新时,我需要能够动态更新和输入一个 table。为此,我需要更新整个条目,以便我可以使用该数据正确更新动态更新的条目。

我正在使用 $afterUpdate 钩子获取较低级别的 table 条目。我遇到的问题是,当我在 $afterUpdate 挂钩函数中记录 this 时,它只包含我要更新的条目部分的属性。我怎样才能得到整个条目?我确定我可以通过 运行 对数据库的额外查询来获取记录,但我希望有办法避免这种情况。任何帮助将不胜感激

我认为,截至目前,您只能通过额外查询获得整个模型。 如果您使用实例查询 ($query) 进行更新,您可以从 options.old.

获取其他属性

查询:

const user = await User.query().findById(userId);
await user.$query()
          .patch({ name: 'Tom Jane' })

挂钩:

$afterUpdate(opt, queryContext) {
  console.log(opt.old)
}

补丁

如果您不需要在钩子中执行此操作,您可能需要使用 patchfirst().returning('*') 链接的函数在单个查询中获取整个模型,它比patchAndFetchById 在 postgreSQL 中。如文档中所述。

Because PostgreSQL (and some others) support returning('*') chaining, you can actually insert a row, or update / patch / delete (an) existing row(s), and receive the affected row(s) as Model instances in a single query, thus improving efficiency. See the examples for more clarity.

const jennifer = await Person
  .query()
  .patch({firstName: 'Jenn', lastName: 'Lawrence'})
  .where('id', 1234)
  .returning('*')
  .first();

参考文献: