在随后的KNEX查询中使用输入语句生成的ID



我有此knex插入:

knex('notes')
  .insert({
    user_id: userId,
    customer_id: customerId,
    product_id: productId,
    note: text,
  })

它将记录添加到具有id列的notes表中。

我想在下一个语句中在此处创建的行中使用id

const response = await knexnest(knex('notes')
  .select([
    'notes.id AS _id',
    'notes.note AS _note',
    'notes.user_id AS _userId',
    'notes.customer_id AS _customerId',
    'notes.product_id AS _productId',
    'notes.timestamp AS _timestamp',
    'tags.id AS _tags__id',
    'tags.title AS _tags__tagTitle',
    'tags.type AS _tags__tagType',
  ])
  .where('notes.id', noteId)
  .innerJoin('note_tags', 'notes.id', 'note_tags.note_id')
  .innerJoin('tags', 'note_tags.tag_id', 'tags.id'));
  return response;

我该怎么做?我知道插入物具有.return()。我认为我可能会将id返回我的原始电话,然后再进行第二个调用来运行选择,但似乎过于复杂。

可悲的是我认为没有较短的解决方案。

您不能在返回子句中使用完整的查询。

const { id } = await knex('notes')
  .returning('id')
  .insert({
    user_id: userId,
    customer_id: customerId,
    product_id: productId,
    note: text,
  })
return knexnest(knex('notes')
  .select([
    'notes.id AS _id',
    'notes.note AS _note',
    'notes.user_id AS _userId',
    'notes.customer_id AS _customerId',
    'notes.product_id AS _productId',
    'notes.timestamp AS _timestamp',
    'tags.id AS _tags__id',
    'tags.title AS _tags__tagTitle',
    'tags.type AS _tags__tagType',
  ])
  .where('notes.id', id)
  .innerJoin('note_tags', 'notes.id', 'note_tags.note_id')
  .innerJoin('tags', 'note_tags.tag_id', 'tags.id'))

最新更新