Laravel 13 + Livewire/Volt app for managing client organizations, documents, passwords, flexible assets, virtual machines, contacts, domains, todos, shortcuts, and role-based user administration.
49 lines
1.4 KiB
PHP
49 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
|
|
|
class RelatedItem extends Model
|
|
{
|
|
protected $guarded = [];
|
|
|
|
public function item(): MorphTo
|
|
{
|
|
return $this->morphTo(__FUNCTION__, 'item_type', 'item_id');
|
|
}
|
|
|
|
public function relatedItem(): MorphTo
|
|
{
|
|
return $this->morphTo(__FUNCTION__, 'related_item_type', 'related_item_id');
|
|
}
|
|
|
|
public function creator()
|
|
{
|
|
return $this->belongsTo(User::class, 'created_by');
|
|
}
|
|
|
|
/**
|
|
* All edges touching a given model, either as owner or as target (symmetric view).
|
|
*/
|
|
public static function forItem(Model $model)
|
|
{
|
|
return static::where(function ($query) use ($model) {
|
|
$query->where('item_type', $model->getMorphClass())->where('item_id', $model->getKey());
|
|
})->orWhere(function ($query) use ($model) {
|
|
$query->where('related_item_type', $model->getMorphClass())->where('related_item_id', $model->getKey());
|
|
});
|
|
}
|
|
|
|
/**
|
|
* The model on the "other side" of this edge, relative to the given model.
|
|
*/
|
|
public function otherItem(Model $relativeTo): ?Model
|
|
{
|
|
$isOwner = $this->item_type === $relativeTo->getMorphClass() && (string) $this->item_id === (string) $relativeTo->getKey();
|
|
|
|
return $isOwner ? $this->relatedItem : $this->item;
|
|
}
|
|
}
|