New-Thanasoft/thanasoft-back/app/Models/FileAttachment.php
2025-12-01 17:02:01 +03:00

142 lines
3.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\MorphTo;
class FileAttachment extends Model
{
use HasFactory;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'file_attachments';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'file_id',
'label',
'attachable_type',
'attachable_id',
'sort_order',
'created_at',
'updated_at',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'sort_order' => 'integer',
];
/**
* Get the parent attachable model (polymorphic).
*/
public function attachable(): MorphTo
{
return $this->morphTo();
}
/**
* Get the file associated with the attachment.
*/
public function file(): BelongsTo
{
return $this->belongsTo(File::class);
}
/**
* Get the intervention associated with the attachment (legacy support).
*/
public function intervention(): BelongsTo
{
return $this->belongsTo(Intervention::class, 'attachable_id')->where('attachable_type', Intervention::class);
}
/**
* Get the client associated with the attachment.
*/
public function client(): BelongsTo
{
return $this->belongsTo(Client::class, 'attachable_id')->where('attachable_type', Client::class);
}
/**
* Get the deceased associated with the attachment.
*/
public function deceased(): BelongsTo
{
return $this->belongsTo(Deceased::class, 'attachable_id')->where('attachable_type', Deceased::class);
}
/**
* Scope to filter by attachable type.
*/
public function scopeOfType($query, string $type)
{
return $query->where('attachable_type', $type);
}
/**
* Scope to filter by attachable model.
*/
public function scopeFor($query, Model $model)
{
return $query->where('attachable_type', get_class($model))
->where('attachable_id', $model->getKey());
}
/**
* Get the display name of the attached model.
*/
public function getAttachableNameAttribute(): string
{
return $this->attachable?->name ?? $this->attachable?->file_name ?? 'Unknown';
}
/**
* Get the URL for downloading the attached file.
*/
public function getDownloadUrlAttribute(): string
{
return url('/api/files/' . $this->file_id . '/download');
}
/**
* Check if this attachment belongs to an intervention.
*/
public function isForIntervention(): bool
{
return $this->attachable_type === Intervention::class;
}
/**
* Check if this attachment belongs to a client.
*/
public function isForClient(): bool
{
return $this->attachable_type === Client::class;
}
/**
* Check if this attachment belongs to a deceased.
*/
public function isForDeceased(): bool
{
return $this->attachable_type === Deceased::class;
}
}