Return 数据来自 Knex 更新中加入的 table

Return data from joined table in Knex update

我有这个 knex 更新:

update = async (noteId, text, db) => (
    db.knex('notes')
      .returning([
        'id',
        'note',
        'user_id',
        'product_id',
        'timestamp',
      ])
      .where('id', noteId)
      .update({
        timestamp: new Date(),
        note: text,
      })
  );

我希望在返回的数据中包含 product_name。这必须来自在 notes.product_id = product.id 上加入的产品 table。如何通过 knex 执行此操作?

Knex 是一个 SQL 查询生成器。这不是 ORM. If you're looking for eager loading, you should check out an ORM like ObjectionJS.

要使用 Knex 执行此操作,您可以像在 SQL 中一样执行此操作。最简单的方法是执行更新。然后,您需要执行 select 和 knex's inner join.

update = async (noteId, text, db) => (
    await db.knex('notes')
      .where('id', noteId)
      .update({
        timestamp: new Date(),
        note: text,
      });

    const response = await db.knex('notes')
      .where('id', noteId)
      .innerJoin('products', 'notes.product_id', 'products.id')
      .first();

    return response;
  );