OptimLock.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace think\model\concern;
  13. use think\db\exception\DbException as Exception;
  14. /**
  15. * 乐观锁
  16. */
  17. trait OptimLock
  18. {
  19. protected function getOptimLockField()
  20. {
  21. return property_exists($this, 'optimLock') && isset($this->optimLock) ? $this->optimLock : 'lock_version';
  22. }
  23. /**
  24. * 数据检查
  25. * @access protected
  26. * @return void
  27. */
  28. protected function checkData(): void
  29. {
  30. $this->isExists() ? $this->updateLockVersion() : $this->recordLockVersion();
  31. }
  32. /**
  33. * 记录乐观锁
  34. * @access protected
  35. * @return void
  36. */
  37. protected function recordLockVersion(): void
  38. {
  39. $optimLock = $this->getOptimLockField();
  40. if ($optimLock) {
  41. $this->set($optimLock, 0);
  42. }
  43. }
  44. /**
  45. * 更新乐观锁
  46. * @access protected
  47. * @return void
  48. */
  49. protected function updateLockVersion(): void
  50. {
  51. $optimLock = $this->getOptimLockField();
  52. if ($optimLock && $lockVer = $this->getOrigin($optimLock)) {
  53. // 更新乐观锁
  54. $this->set($optimLock, $lockVer + 1);
  55. }
  56. }
  57. public function getWhere()
  58. {
  59. $where = parent::getWhere();
  60. $optimLock = $this->getOptimLockField();
  61. if ($optimLock && $lockVer = $this->getOrigin($optimLock)) {
  62. $where[] = [$optimLock, '=', $lockVer];
  63. }
  64. return $where;
  65. }
  66. protected function checkResult($result): void
  67. {
  68. if (!$result) {
  69. throw new Exception('record has update');
  70. }
  71. }
  72. }