在typeorm中对当前字段的更新

  • 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);
          });
      }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值