UserMoneyLog.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. * UserMoneyLog 模型
  9. * 1. 创建余额日志自动完成会员余额的添加
  10. * 2. 创建余额日志时,请开启事务
  11. */
  12. class UserMoneyLog 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->money;
  30. $user->money += $model->money;
  31. $user->save();
  32. $model->after = $user->money;
  33. }
  34. public static function onBeforeDelete(): bool
  35. {
  36. return false;
  37. }
  38. public function getMoneyAttr($value): string
  39. {
  40. return bcdiv($value, 100, 2);
  41. }
  42. public function setMoneyAttr($value): string
  43. {
  44. return bcmul($value, 100, 2);
  45. }
  46. public function getBeforeAttr($value): string
  47. {
  48. return bcdiv($value, 100, 2);
  49. }
  50. public function setBeforeAttr($value): string
  51. {
  52. return bcmul($value, 100, 2);
  53. }
  54. public function getAfterAttr($value): string
  55. {
  56. return bcdiv($value, 100, 2);
  57. }
  58. public function setAfterAttr($value): string
  59. {
  60. return bcmul($value, 100, 2);
  61. }
  62. public function user(): BelongsTo
  63. {
  64. return $this->belongsTo(User::class, 'user_id');
  65. }
  66. }