FundLogModel.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace App\Module\Fund\Models;
  3. use App\Module\User\Models\User;
  4. use App\Module\User\Models\UserInfo;
  5. use UCore\ModelCore;
  6. /**
  7. * 资金日志表
  8. *
  9. * @property int $id
  10. * @property int $user_id 用户ID
  11. * @property int $fund_id 资金id
  12. * @property int $amount 操作金额,正值为收入,负值为支出
  13. * @property string $operate_id 上游操作id
  14. * @property string $operate_type 上游操作类型
  15. * @property string $remark 备注
  16. * @property int $create_time 最后更新时间
  17. * @property string $create_ip 最后更新ip
  18. * @property int $later_balance 在此之后的余额
  19. * @property int $before_balance 在此之前的余额
  20. * @property int $date_key 月份key
  21. * @property string $hash 防篡改哈希值
  22. * @property string $prev_hash 上一条记录的哈希值
  23. */
  24. class FundLogModel extends ModelCore
  25. {
  26. protected $table = 'fund_logs';
  27. public $timestamps = false;
  28. protected $fillable = [
  29. 'user_id',
  30. 'fund_id',
  31. 'amount',
  32. 'operate_id',
  33. 'operate_type',
  34. 'remark',
  35. 'create_time',
  36. 'create_ip',
  37. 'later_balance',
  38. 'before_balance',
  39. 'date_key',
  40. 'hash',
  41. 'prev_hash'
  42. ];
  43. public function user()
  44. {
  45. return $this->hasOne(\App\Module\User\Model\User::class, 'user_id', 'user_id');
  46. }
  47. /**
  48. * 生成记录的哈希值
  49. * SHA-256 输出为 64 位十六进制字符串
  50. */
  51. public function generateHash(): string
  52. {
  53. $data = [
  54. 'id' => $this->id,
  55. 'user_id' => $this->user_id,
  56. 'fund_id' => $this->fund_id,
  57. 'amount' => $this->amount,
  58. 'operate_id' => $this->operate_id,
  59. 'operate_type' => $this->operate_type,
  60. 'before_balance' => $this->before_balance,
  61. 'later_balance' => $this->later_balance,
  62. 'create_time' => $this->create_time,
  63. 'create_ip' => $this->create_ip,
  64. 'prev_hash' => $this->prev_hash,
  65. ];
  66. // 按键名排序,确保生成的哈希值一致
  67. ksort($data);
  68. // 生成 64 位十六进制哈希值
  69. return hash('sha256', json_encode($data, JSON_UNESCAPED_UNICODE));
  70. }
  71. /**
  72. * @param $user_id
  73. * @param $fund_id
  74. * @return static
  75. */
  76. public static function findLastUserFund($user_id, $fund_id)
  77. {
  78. return self::query()->where([
  79. 'user_id' => $user_id,
  80. 'fund_id' => $fund_id
  81. ])->orderBy('id', 'desc')->first();
  82. }
  83. public static function addLog($userId,$fundId,$amount,)
  84. {
  85. }
  86. }