49 lines
1.2 KiB
PHP
49 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Veelasky\LaravelHashId\Eloquent\HashableId;
|
|
|
|
class Membership extends Model
|
|
{
|
|
use HasFactory, HashableId, SoftDeletes;
|
|
|
|
protected $guarded = ['id'];
|
|
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'total_spending' => 'int',
|
|
'reward_points' => 'int',
|
|
];
|
|
}
|
|
|
|
public function recalculateTier(): void
|
|
{
|
|
$newTier = Tier::where('min_spending', '<=', $this->total_spending)
|
|
->where(function ($query) {
|
|
$query->whereNull('max_spending')
|
|
->orWhere('max_spending', '>=', $this->total_spending);
|
|
})
|
|
->first();
|
|
|
|
if ($newTier && $newTier->id !== $this->tier_id) {
|
|
$this->update(['tier_id' => $newTier->id]);
|
|
}
|
|
}
|
|
|
|
public function tier(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Tier::class);
|
|
}
|
|
|
|
public function user(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
}
|