UserScoreLog.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace app\admin\model;
  3. use Throwable;
  4. use think\model;
  5. use think\Exception;
  6. use think\model\relation\BelongsTo;
  7. /**
  8. * UserScoreLog 模型
  9. * 1. 创建积分日志自动完成会员积分的添加
  10. * 2. 创建积分日志时,请开启事务
  11. */
  12. class UserScoreLog extends model
  13. {
  14. protected $autoWriteTimestamp = true;
  15. protected $updateTime = false;
  16. /**
  17. * 入库前
  18. * @throws Throwable
  19. */
  20. public static function onBeforeInsert($model)
  21. {
  22. $user = User::where('id', $model->user_id)->lock(true)->find();
  23. if (!$user) {
  24. throw new Exception("The user can't find it");
  25. }
  26. if (!$model->memo) {
  27. throw new Exception("Change note cannot be blank");
  28. }
  29. $model->before = $user->score;
  30. $user->score += $model->score;
  31. $user->save();
  32. $model->after = $user->score;
  33. }
  34. public static function onBeforeDelete(): bool
  35. {
  36. return false;
  37. }
  38. public function user(): BelongsTo
  39. {
  40. return $this->belongsTo(User::class, 'user_id');
  41. }
  42. }