User.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. //从生日转成年龄
  14. public function getAgeAttribute()
  15. {
  16. return birthday_to_age($this->birthday);
  17. }
  18. public function getCouponNumAttribute()
  19. {
  20. return UserCoupon::where('user_id', $this->id)->where('status', 1)->where('expire_time', '>', time())->count();
  21. }
  22. //通过token获取用户信息
  23. public static function getUserByToken($is_exit = true)
  24. {
  25. $auth = request()->header('token');
  26. if (empty($auth)) {
  27. if (!$is_exit) {
  28. return [];
  29. }
  30. exit_out(null, 401, '认证失效,请重新登录');
  31. }
  32. $arr = aes_decrypt($auth);
  33. if (empty($arr['id'])) {
  34. if (!$is_exit) {
  35. return [];
  36. }
  37. exit_out(null, 401, '认证失效,请重新登录');
  38. }
  39. $user = User::where('id', $arr['id'])->first();
  40. if (empty($user)){
  41. exit_out(null, 601, '该账号已被删除');
  42. }
  43. $user = $user->toArray();
  44. if ($user['status'] == 0){
  45. exit_out(null, 602, '该账号已被冻结');
  46. }
  47. return $user;
  48. }
  49. //改变用户余额
  50. public static function changeBalance($user_id, $change_balance, $type, $relation_id, $remark, $admin_user_id = 0)
  51. {
  52. $user = User::select(['balance'])->where('id', $user_id)->first();
  53. if ($type == 2) {
  54. User::where('id', $user_id)->update([
  55. 'balance' => DB::raw('balance + '.$change_balance),
  56. 'topup_balance' => DB::raw('topup_balance + '.$change_balance),
  57. ]);
  58. }
  59. elseif ($type == 3) {
  60. User::where('id', $user_id)->update([
  61. 'balance' => DB::raw('balance + '.$change_balance),
  62. 'giving_balance' => DB::raw('giving_balance + '.$change_balance),
  63. ]);
  64. }
  65. else {
  66. User::where('id', $user_id)->increment('balance', $change_balance);
  67. }
  68. UserBalanceLog::create([
  69. 'user_id' => $user_id,
  70. 'admin_user_id' => $admin_user_id,
  71. 'type' => $type,
  72. 'relation_id' => $relation_id,
  73. 'before_balance' => $user['balance'],
  74. 'change_balance' => $change_balance,
  75. 'after_balance' => $user['balance'] + $change_balance,
  76. 'remark' => $remark,
  77. ]);
  78. return true;
  79. }
  80. public function UserBalanceLog(){
  81. return $this->hasMany(UserBalanceLog::class);
  82. }
  83. }