ldc-crm/app/Models/ClaimSubject.php

107 lines
2.7 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
/**
* @property integer $id Subject id.
* @property string $label Subject label.
* @property \App\Models\Brand $brand_id Subject associated Brand.
* @property-read \Illuminate\Support\Carbon $created_at Subject created date.
* @property-read \Illuminate\Support\Carbon $updated_at Subject updated date.
*/
class ClaimSubject extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'label',
'brand_id',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::created(function () {
self::resetCache();
});
static::updated(function () {
self::resetCache();
});
static::deleted(function () {
self::resetCache();
});
}
// * METHODS
/**
* Get all subjects associated to the band.
*
* @param integer $brandModelKey
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getAllModelsFromBrand(int $brandModelKey): \Illuminate\Database\Eloquent\Collection
{
return self::getSubjects()->filter(
fn($model) => $model->brand->getKey() === $brandModelKey
)->values();
}
/**
* Reset all cache elements related to this model.
*
* @return void
*/
private static function resetCache(): void
{
Cache::forget('subjects');
self::getSubjects();
}
/**
* Get all subjects.
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getSubjects(): \Illuminate\Database\Eloquent\Collection
{
return Cache::remember('subjects', 86400, function () {
return self::query()->orderBy('label', 'ASC')->get();
});
}
// * RELATIONS
/**
* Brand belongs to relation.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function brand(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Brand::class);
}
/**
* Claim has many relation.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function claims(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Claim::class);
}
}