User.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zilongs
  5. * Date: 20-9-23
  6. * Time: 上午11:04
  7. */
  8. namespace App\Models;
  9. use DB;
  10. class User extends BaseModel
  11. {
  12. protected $appends = ['age'];
  13. public function getAgeAttribute()
  14. {
  15. return birthday_to_age($this->birthday);
  16. }
  17. public function getCouponNumAttribute()
  18. {
  19. return UserCoupon::where('user_id', $this->id)->where('status', 1)->where('expire_time', '>', time())->count();
  20. }
  21. //通过token获取用户信息
  22. public static function getUserByToken($is_exit = true)
  23. {
  24. $auth = request()->header('token');
  25. if (empty($auth)) {
  26. if (!$is_exit) {
  27. return [];
  28. }
  29. exit_out(null, 401, '认证失效,请重新登录');
  30. }
  31. $arr = aes_decrypt($auth);
  32. if (empty($arr['id'])) {
  33. if (!$is_exit) {
  34. return [];
  35. }
  36. exit_out(null, 401, '认证失效,请重新登录');
  37. }
  38. $user = User::where('id', $arr['id'])->first();
  39. if (empty($user)){
  40. exit_out(null, 601, '该账号已被删除');
  41. }
  42. $user = $user->toArray();
  43. if ($user['status'] == 0){
  44. exit_out(null, 602, '该账号已被冻结');
  45. }
  46. return $user;
  47. }
  48. //改变用户余额
  49. public static function changeBalance($user_id, $change_balance, $type, $relation_id, $remark, $admin_user_id = 0)
  50. {
  51. $user = User::select(['balance'])->where('id', $user_id)->first();
  52. if ($type == 2) {
  53. User::where('id', $user_id)->update([
  54. 'balance' => DB::raw('balance + '.$change_balance),
  55. 'topup_balance' => DB::raw('topup_balance + '.$change_balance),
  56. ]);
  57. }
  58. elseif ($type == 3) {
  59. User::where('id', $user_id)->update([
  60. 'balance' => DB::raw('balance + '.$change_balance),
  61. 'giving_balance' => DB::raw('giving_balance + '.$change_balance),
  62. ]);
  63. }
  64. else {
  65. User::where('id', $user_id)->increment('balance', $change_balance);
  66. }
  67. UserBalanceLog::create([
  68. 'user_id' => $user_id,
  69. 'admin_user_id' => $admin_user_id,
  70. 'type' => $type,
  71. 'relation_id' => $relation_id,
  72. 'before_balance' => $user['balance'],
  73. 'change_balance' => $change_balance,
  74. 'after_balance' => $user['balance'] + $change_balance,
  75. 'remark' => $remark,
  76. ]);
  77. return true;
  78. }
  79. }