auditionadmin/app/Models/ScoreSheet.php

77 lines
2.2 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Support\Facades\Cache;
class ScoreSheet extends Model
{
protected $fillable = [
'user_id',
'entry_id',
'subscores',
'sheet_total',
];
protected $casts = ['subscores' => 'json'];
protected static function boot()
{
parent::boot();
static::created(function ($scoreSheet) {
$scoreSheet->deleteRelatedCalculatedScores();
});
static::updated(function ($scoreSheet) {
$scoreSheet->deleteRelatedCalculatedScores();
});
static::deleted(function ($scoreSheet) {
$scoreSheet->deleteRelatedCalculatedScores();
});
}
public function entry(): BelongsTo
{
return $this->belongsTo(Entry::class);
}
public function judge(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
public function audition(): HasOneThrough
{
return $this->hasOneThrough(
Audition::class, // The final model you want to access
Entry::class, // The intermediate model
'id', // Foreign key on the intermediate model (Entry)
'id', // Foreign key on the final model (Audition)
'entry_id', // Local key on the current model (ScoreSheet)
'audition_id' // Local key on the intermediate model (Entry)
);
}
public function getSubscore($id)
{
return $this->subscores[$id]['score'] ?? false;
// this function is used at resources/views/tabulation/entry_score_sheet.blade.php
}
public function deleteRelatedCalculatedScores(): void
{
$entry = $this->entry;
if ($entry) {
$entry->calculatedScores()->delete();
Cache::forget('entryScore-'.$entry->id.'-seating');
Cache::forget('entryScore-'.$entry->id.'-advancement');
Cache::forget('audition'.$entry->audition_id.'seating');
Cache::forget('audition'.$entry->audition_id.'advancement');
}
}
}