top-think / top-think/think-orm

Model在循环内执行自增/自减操作后的save问题

Open
#792 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
PHP
Stars
437
Forks
188
PR merge metrics
No merged PRs in 30d

Description

模拟一个扣库存动作

 for ($i = 0; $i < 10; $i++) {
            $info = (new MerchantGoods())->where('id', 1)->findOrEmpty();
            $info->dec('stock_qty', 1)->save();
        }

上面的写法执行后无论库存数是都是,最终均会被设置成1
跟踪后发现最后一次执行的update语句为UPDATE b_merchant_goods SET stock_qty = '1' WHERE id = '1'

改写成一下方式则符合预期

  for ($i = 0; $i < 10; $i++) {
            $info = (new MerchantGoods())->where('id', 1)->findOrEmpty();
            $info->save([
                'stock_qty' => Db::Raw('stock_qty -1'),
            ]);
        }

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the issue's loop reproduction and compare the generated update for dec('stock_qty', 1)->save() with the Db::Raw alternative. No source file or test is named; trace the dec and save entry points, then add coverage showing repeated iterations preserve each decrement instead of resetting the value.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
backend, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.