Exp.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Support\Facades\DB;
  5. class Exp extends Model
  6. {
  7. protected $table = 'tb_exp';
  8. protected $primaryKey = 'id';
  9. public $keyType = 'int';
  10. public $incrementing = true;
  11. public $timestamps = true;
  12. const CREATED_AT = 'created_at';
  13. const UPDATED_AT = null;
  14. protected $guarded = [];
  15. /**
  16. * 경험치를 추가합니다.
  17. */
  18. public function register(array $params): bool
  19. {
  20. // 이미 등록된 내역이라면 건너뜀
  21. if($this->where([
  22. ['user_id', $params['user_id']],
  23. ['type', $params['type']],
  24. ['related_id', $params['related_id']],
  25. ['method', $params['method']],
  26. ])->exists()) {
  27. return false;
  28. }
  29. if(!$this->insert($params)) {
  30. return false;
  31. }
  32. return $this->updateUserExp($params['user_id']);
  33. }
  34. /**
  35. * 회원 경험치를 삭제합니다.
  36. */
  37. public function remove(array $params)
  38. {
  39. $this->where([
  40. ['user_id', $params['user_id']],
  41. ['type', $params['type']],
  42. ['related_id', $params['related_id']],
  43. ['method', $params['method']],
  44. ])->delete();
  45. return $this->updateUserExp($params['user_id']);
  46. }
  47. /**
  48. * 회원 경험치 갱신
  49. */
  50. public function updateUserExp(int $userID)
  51. {
  52. return (new User)->where('id', $userID)->update([
  53. 'exp' => $this->getUserExpSum($userID)
  54. ]);
  55. }
  56. /**
  57. * 회원 경험치 합계
  58. */
  59. public function getUserExpSum(int $userID): int
  60. {
  61. $sql = "SELECT COALESCE(SUM(`value`), 0) AS total FROM tb_exp WHERE user_id = ?;";
  62. return DB::selectOne($sql, [$userID])->total;
  63. }
  64. }