knex 使用 count() 结果作为插入新行的值

knex use count() result as a value for inserting a new row

我正在尝试使用 count() 结果作为插入新行的值。 问题是,在多线程的情况下,我得到了错误的 count() 值,因为当前代码无法正常处理事务。

我已经尝试了很多方法来实现带和不带显式 knex 事务的锁定,但无法获得正确的 count() 值。

  const now = knex.fn.now();

  const [{ count }] = await knex
    .count()
    .from(STUDENTS)
    .where(CLASS_ID_COL, classId)
    .then(daoUtils.normalize);

  const [id] = await knex
    .insert(
      {
        [CREATED_AT_COL]: now,
        [UPDATED_AT_COL]: now,
        [CLASS_ID_COL]: classId,
        [ORDER_COL]: Number(count)
      },
      ID_COL
    )
    .into(STUDENTS);

提前致谢。

我找到了使用 .forUpdate() 的解决方案:

const now = knex.fn.now();

return knex.transaction(async trx => {

    const [id] = await knex
      .insert(
        {
          [CREATED_AT_COL]: now,
          [UPDATED_AT_COL]: now,
          [CLASS_ID_COL]: classId,
          [ORDER_COL]: Number(count)
        },
        ID_COL
      )
      .into(STUDENTS);

    const result = await trx
      .select("*")
      .forUpdate()
      .from(STUDENTS)
      .where(CLASS_ID_COL, classId);


    await trx.table(STUDENTS)
      .update(ORDER_COL, Number(result.length) - 1)
      .where(ID_COL, id);

    return id;

  });