資料編號+1 併發問題解決

半人間發表於2019-09-10
        //正常寫法,獲取最後一條資料,新的單據編號+1,有併發問題
        $last = Article::orderByDesc('id')->first();
        $data = [
            'code'    => $last->code + 1,
        ];
        $article = Article::create($data);

        //---------------------------------------------------------------------------------//
        //解決併發問題  測試ab -t 6 -c 20 http://study.local/xxx
        DB::beginTransaction();
        $last = Article::lockForUpdate()->orderByDesc('id')->first();
        $data = [
            'code'    => $last->code + 1,
        ];
        $article = Article::create($data);
        DB::commit();

相關文章