Home:ALL Converter>Return data from joined table in Knex update

Return data from joined table in Knex update

Ask Time:2019-07-30T16:55:55         Author:runnerpaul

Json Formatter

I have this knex update:

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,
      })
  );

In the returned data I wish to include product_name. This has to come from a product table which is joined on notes.product_id = product.id. How do I do this through knex?

Author:runnerpaul,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/57267873/return-data-from-joined-table-in-knex-update
technogeek1995 :

Knex is a SQL query builder. It's not an ORM. If you're looking for eager loading, you should check out an ORM like ObjectionJS.\n\nTo do this with Knex, you would do it the same as you do in SQL. The simplest way is to perform the update. Then, you'll need to perform a select and knex's inner join.\n\nupdate = async (noteId, text, db) => (\n await db.knex('notes')\n .where('id', noteId)\n .update({\n timestamp: new Date(),\n note: text,\n });\n\n const response = await db.knex('notes')\n .where('id', noteId)\n .innerJoin('products', 'notes.product_id', 'products.id')\n .first();\n\n return response;\n );\n",
2019-07-30T14:01:46
yy