lockForUpdate 是悲观锁,测试就不写了
注意的事项
- lockForUpdate 必须在事务中
- lockForUpdate 被阻塞的查询必须是同样添加了lockForUpdate的语句
- 查询语句走索引,则使用行锁,否则使用表锁
现在举例说明第一项和第二项
开启事务并添加锁
public function test1(){DB::beginTransaction();try {$user = GameUser::lockForUpdate()->where('name', "李涛")->first();sleep(10);DB::commit();echo "over!";} catch (\Exception $e) {DB::rollBack();}}
下面不锁定数据的情况
// 不加lockForUpdate,不锁定
GameUser::where('id', 1)->first();
// where 查询条件不一样,不锁定
GameUser::lockForUpdate()->where('name', 'test')->first();
表锁、行锁
搜索条件有索引,则走行锁。没有走表锁
但是注意一些导致索引失效的情况下,例如使用<>不等于查询id,也会走表锁