grant medal

This commit is contained in:
xiaomlove
2022-01-25 23:37:50 +08:00
parent 64a1f2bb0c
commit 27ba9aec74
10 changed files with 3024 additions and 2761 deletions

View File

@@ -2,7 +2,9 @@
namespace App\Repositories;
use App\Models\Medal;
use App\Models\User;
use App\Models\UserMedal;
use Carbon\Carbon;
use Nexus\Database\NexusDB;
class MedalRepository extends BaseRepository
@@ -51,4 +53,20 @@ class MedalRepository extends BaseRepository
return true;
}
public function grantToUser(int $uid, int $medalId, $duration = null)
{
$user = User::query()->findOrFail($uid, User::$commonFields);
$medal = Medal::query()->findOrFail($medalId);
$exists = $user->valid_medals()->where('medal_id', $medalId)->exists();
do_log(last_query());
if ($exists) {
throw new \LogicException("user: $uid already own this medal: $medalId.");
}
$expireAt = null;
if ($duration > 0) {
$expireAt = Carbon::now()->addDays($duration)->toDateTimeString();
}
return $user->medals()->attach([$medal->id => ['expire_at' => $expireAt]]);
}
}