1 public static function alter($aid, $rid) 2 { 3 $incDec = GoldRule::where(['gold_rule_isdel'=>1,'gold_rule_status'=>2]) 4 ->where('gold_rule_id', $rid) 5 ->value('gold_rule_num'); 6 $isHas = self::where('gold_aid', $aid)->find(); 7 8 $model = new Gold(); 9 if ($isHas) { 10 try{ 11 $model->startTrans();//開啓事務 12 $gold = $model->lock(true)->where('gold_aid', $aid)->find();//加鎖 13 $res = $gold->where('gold_aid', $aid)->update(['gold_number' => $isHas['gold_number'] + $incDec]);//執行更新 14 //sleep(5);//可使用sleep()函數來驗證是否加成功鎖 第二次更新會等待第一次更新完成 15 $model->commit();//事務提交 16 return $res; 17 }catch(\Exception $exception){ 18 $model->rollback(); 19 throw $exception; 20 } 21 } else { 22 23 $model->gold_aid = $aid; 24 $model->gold_number = $incDec; 25 return $model->save(); 26 } 27 }