我尝试使用count() result作为插入新行的值。问题是,在多线程的情况下,我得到了一个错误的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);
提前谢谢。
发布于 2019-06-23 22:47:46
我找到了一个使用.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;
});
https://stackoverflow.com/questions/56723889
复制相似问题