首先我们了解一下数据库的锁,数据库是一个多用户使用的共享资源。当多个用户并发地存取数据时,在数据库中就会产生多个事务同时存取同一数据的情况。若对并发操作不加控制就可能会读取和存储不正确的数据,破坏数据库的一致性,(注意事项:首先,数据库类型要是InnoDB,其次,加锁必须跟事务同时使用)。
在tp5中如何使用:请看以下代码
public function testTrans(){
$time = date('H:i:s');
$model = new \app\model\Student();
$model->startTrans();//开启事务
try{
$student = $model->lock(true)->where('id', 4)->find();//加锁
$student->update(['age' => $student['age']+10], ['id' => 4]);
sleep(20);
$model->commit();//事务提交
return $time.'_lock_true_'.date('H:i:s');
} catch (\Exception $e) {
$model->rollback();
throw $e;
}
return $time.'_lock_false_'.date('H:i:s');
}
当我们在浏览器中先运行该方法,立即再打开窗口在运行一次,我们看一下结果如下图
我们发现第二次会在一次运行完之后,也就是在等待20s,事务提交后才会进行操作
参考链接:http://www.thinkphp.cn/topic/46363.html