1. /**
  2.  * thinkphp使用悲观锁。悲观锁需要配合事务一起使用
  3.  * 商品表。购买数量为1,先锁定该商品,不让其他操作减库存。
  4.  */
  5. public function mysql_lock(){
  6.     $num = 1;   //数量
  7.     $goods_id = 1;   //商品id
  8.     $model = \db('goods');
  9.     $model->execute('set autocommit=0;');   //事物非自动提交
  10.     $model->startTrans();
  11.     //使用主键或者其他索引字段时为行级锁,否则为表级锁
  12.     $where['id'] = $goods_id;
  13.     $where['status'] = 1;
  14.     $goods_info = $model->lock(true)->where($where)->find();
  15.     if(empty($goods_info)){
  16.         return '商品不存在';
  17.     }
  18.     $total = $goods_info['goods_num'];  //商品库存
  19.     $sell = $goods_info['sell'];    //商品销量
  20.     if($total<$num){
  21.         return '库存不足';
  22.     }
  23.     $data['goods_num'] = $total-$num;
  24.     $data['sell'] = $sell+$num;
  25.     $res = $model->where(array('id'=>$goods_id))->update($data);
  26.     if($res){
  27.         $order_model = \db('orders');
  28.         $order_data['uid'] = rand(1000,9999);
  29.         $order_data['status'] = 1;
  30.         $order_data['create_time'] = date('Y-m-d H:i:s');
  31.         $order_res = $order_model->insert($order_data);
  32.         if($order_res){
  33.             $model->commit();
  34.             return json(['code'=>1,'msg'=>'成功']);
  35.         }else{
  36.  
  37.             $model->rollback();
  38.             return json(['code'=>0,'msg'=>'失败']);
  39.         }
  40.     }else{
  41.  
  42.         $model->rollback();
  43.         return json(['code'=>0,'msg'=>'失败']);
  44.     }
  45.     exit;
  46.  
  47. }


相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!