-
1、普通的
sql
语句update goods set count = count - 10 where id = 1;
-
2、在
typeorm
中写法方式一// 使用mysql的乐观锁实现 async goods(): Promise<string> { const num = 90; const goodsInfo: Pick<GoodsEntity, 'count' | 'version'> = await this.goodsRepository.findOne({ where: { id: 1 }, select: ['count', 'version'], }); while (true) { if (goodsInfo.count < num) { console.log(`当前库存只有:${goodsInfo.count},你下单数量为:${num}`); throw new HttpException( `当前库存只有:${goodsInfo.count},你下单数量为:${num}`, HttpStatus.OK, ); } else { // 更新数据库 // 或者使用this.goodsRepository.createQueryBuilder() const { raw: { affectedRows }, } = await getConnection() .createQueryBuilder() .update(GoodsEntity) .set({ count: () => `count - ${num}`, version: () => `version+1` }) .where('id=:id', { id: 1, version: goodsInfo.version }) .execute(); if (affectedRows) { break; } } } return '下单成功'; }
-
、方式二
async goods1(): Promise<string> { return getConnection() .transaction(async (entityManager: EntityManager) => { const num = 90; const goodsInfo: Pick<GoodsEntity, 'count' | 'version'> = await this.goodsRepository.findOne({ where: { id: 1 }, select: ['count', 'version'], }); while (true) { if (goodsInfo.count < num) { console.log(`当前库存只有:${goodsInfo.count},你下单数量为:${num}`); throw new HttpException( `当前库存只有:${goodsInfo.count},你下单数量为:${num}`, HttpStatus.OK, ); } else { const { raw: { affectedRows }, } = await entityManager.update<GoodsEntity>( GoodsEntity, { id: 1, version: goodsInfo.version }, { count: () => `count - ${num}`, version: () => `version+1` }, ); if (affectedRows) { break; } } } }) .then(async () => { return '下单成功'; }) .catch((e) => { console.log(e); throw new HttpException('下单失败', HttpStatus.OK); }); }
在typeorm中对当前字段的更新
最新推荐文章于 2023-04-17 00:48:41 发布