MoneyLog.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\common\model;
  4. use think\Model;
  5. class MoneyLog Extends Model
  6. {
  7. // 自动写入时间戳字段
  8. protected $autoWriteTimestamp = true;
  9. protected $createTime = 'createtime';
  10. protected $updateTime = 'updatetime';
  11. protected $type = [
  12. 'createtime' => 'timestamp:Y-m-d H:i',
  13. 'updatetime' => 'timestamp:Y-m-d H:i',
  14. ];
  15. const TYPE_INCOME = 1;
  16. const TYPE_EXPENDITURE = 2;
  17. //
  18. public function users()
  19. {
  20. return $this->hasOne(User::class,'id','user_id')->field('id,nickname');
  21. }
  22. public function stockconfig()
  23. {
  24. return $this->hasOne(StockConfig::class,'id','variety_id')->field('id,title');
  25. }
  26. //按照类型月统计 收入- 支出
  27. public static function getCountMonthBalance(int $user_id = 0, string $time = '')
  28. {
  29. $income = self::where('type', self::TYPE_INCOME);
  30. if(!empty($user_id) && !empty($time)){
  31. $income = $income->where('user_id', $user_id)->whereMonth('create_date', $time);
  32. }
  33. $income = $income->sum('change');
  34. //支出
  35. $expenditure = self::where('type', self::TYPE_EXPENDITURE);
  36. if(!empty($user_id) && !empty($time)){
  37. $expenditure = $expenditure->where('user_id', $user_id)->whereMonth('create_date', $time);
  38. }
  39. $expenditure = $expenditure->sum('change');
  40. $balance = $income - $expenditure;
  41. return [
  42. 'balance' => $balance,
  43. 'income' => $income,
  44. 'expenditure' => $expenditure
  45. ];
  46. }
  47. //按照类型年统计 收入- 支出
  48. public static function getCountYearBalance(int $user_id = 0, string $time = '')
  49. {
  50. $income = self::where('type', self::TYPE_INCOME);
  51. if(!empty($user_id) && !empty($time)){
  52. $income = $income->where('user_id', $user_id)->whereYear('create_date', $time);
  53. }
  54. $income = $income->sum('change');
  55. //支出
  56. $expenditure = self::where('type', self::TYPE_EXPENDITURE);
  57. if(!empty($user_id) && !empty($time)){
  58. $expenditure = $expenditure->where('user_id', $user_id)->whereYear('create_date', $time);
  59. }
  60. $expenditure = $expenditure->sum('change');
  61. $balance = $income - $expenditure;
  62. return [
  63. 'balance' => $balance,
  64. 'income' => $income,
  65. 'expenditure' => $expenditure
  66. ];
  67. }
  68. }