thinkphp5 在模型操作中使用锁
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 }