47 lines
1.3 KiB
PHP
47 lines
1.3 KiB
PHP
<?php
|
||
|
||
namespace app\admin\model;
|
||
|
||
use think\Exception;
|
||
use think\model;
|
||
use think\model\relation\BelongsTo;
|
||
use Throwable;
|
||
use app\admin\model\UserScoreLog;
|
||
|
||
/**
|
||
* UserScoreLog 模型
|
||
* 1. 创建积分日志自动完成会员积分的添加
|
||
* 2. 创建积分日志时,请开启事务
|
||
*/
|
||
class UserScore extends model
|
||
{
|
||
protected $updateTime = false;
|
||
|
||
/**
|
||
* 更新前
|
||
* @throws Throwable
|
||
*/
|
||
public static function onBeforeUpdate($model): void
|
||
{
|
||
$before = $model->getOrigin('score');
|
||
$after = $model->score;
|
||
// 1. 只有当分数确实发生变化时才记录日志
|
||
if (bccomp($before, $after, 2) !== 0) {
|
||
// 计算分值变动(after - before)
|
||
$change = bcsub($after, $before);
|
||
$userScoreLog = new UserScoreLog();
|
||
$userScoreLog->save([
|
||
'user_id' => $model->user_id,
|
||
'game_type' => $model->game_type,
|
||
'before' => $before,
|
||
'after' => $after,
|
||
'score' => $change,
|
||
'memo' => '管理员手动调整', // 建议增加备注字段区分来源
|
||
]);
|
||
}
|
||
}
|
||
public function user(): BelongsTo
|
||
{
|
||
return $this->belongsTo(User::class, 'user_id');
|
||
}
|
||
} |