Files
yusheng-php/application/api/model/UserDailyIncome.php
2026-01-08 11:59:42 +08:00

98 lines
2.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\api\model;
use think\Model;
class UserDailyIncome extends Model
{
// 定义表名(如果表名和模型名一致可省略,这里显式定义更清晰)
protected $name = 'user_daily_income';
// 开启自动时间戳TP5.1默认用时间戳格式对应create_time/update_time
protected $autoWriteTimestamp = true;
// 定义字段类型转换(确保金额为浮点型)
protected $type = [
'income' => 'float',
'user_id' => 'integer',
];
/**
* 累加用户当日收益(核心方法)
* @param int $userId 用户ID
* @param float $amount 新增收益金额(正数)
* @return bool
*/
public function addDailyIncome($userId, $amount)
{
$today = date('Y-m-d'); // 今日日期
$today_res = $this->where([
'user_id' => $userId,
'date' => $today
])->find();
if($today_res){
$res = $this->where([
'user_id' => $userId,
'date' => $today
])->update([
'income' => $amount,
'update_time'=> time(),
]);
if($res){return true;}
}else{
$res = $this->insert([
'user_id' => $userId,
'income' => $amount,
'date' => $today,
'create_time'=> time(),
'update_time'=> time(),
]);
if($res){return true;}
}
return false;
}
/**
* 查询用户今日收益
* @param int $userId 用户ID
* @param string $today 日期格式YYYY-MM-DD
* @return float 今日收益无收益则返回0
*/
public function getTodayIncome($userId, $today = 0)
{
if (!$today) {
$today = date('Y-m-d');
}
$result = $this->where([
'user_id' => $userId,
'date' => $today
])->value('income');
return $result ? floatval($result) : 0.00;
}
/**
* 查询用户时间段内的收益总和
* @param int $userId 用户ID
* @param string $startDate 开始日期格式YYYY-MM-DD
* @param string $endDate 结束日期格式YYYY-MM-DD
* @return float 时间段总收益无收益则返回0
*/
public function getIncomeByPeriod($userId, $startDate, $endDate)
{
// 校验日期格式(可选,增强健壮性)
if (!strtotime($startDate) || !strtotime($endDate)) {
return 0.00;
}
$total = $this->where([
'user_id' => $userId,
'date' => ['between', [$startDate, $endDate]]
])->sum('income');
return $total ? floatval($total) : 0.00;
}
}