ldc-com-app-bo/app/Models/Directory.php
2023-03-31 16:52:46 +02:00

132 lines
2.8 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* @property integer $id
* @property string $name
* @property integer $parent_id
* @property integer $order
* @property boolean $needAuthorization
*/
class Directory extends Model
{
use HasFactory;
/**
* The accessors to append to the model's array form.
*
* @var string[]
*/
protected $appends = ['is_system'];
/**
* Fillable;
*
* @var string[]
*/
protected $fillable = [
'name',
'parent_id',
'order',
'needAuthorization'
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'name' => 'array'
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function (self $model) {
self::setOrder($model);
});
static::deleting(function (self $tag) {
$tag->appusers()->detach();
});
}
// * METHODS
/**
* Asserts using validation that the field is unique.
*
* @param string $nameField
* @param string $valueField
* @param integer|null $id
* @return void
*/
private static function assertFieldIsUnique(string $nameField, string $valueField, ?int $id = null)
{
$table = (new self())->getTable();
ToolboxHelper::assertFieldIsUnique($table, $nameField, $valueField, $id);
}
/**
* Set order after the last element of the list.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
private static function setOrder(Model $model): void
{
$model->order = \intval(self::query()->max('order')) + 1;
}
/**
* Check if is directory system.
* 1 = Salon
*
* @return boolean
*/
public function getIsSystemAttribute()
{
return $this->id === 1;
}
// * RELATIONSHIPS
/**
* One To Many Relationship Method.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function parent()
{
return $this->belongsTo('App\Models\Directory', 'parent_id');
}
/**
* Has Many Relationship Method.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function children()
{
return $this->hasMany('App\Models\Directory', 'parent_id');
}
/**
* MorphedByMany appusers relation
*
* @return \Illuminate\Database\Eloquent\Relations\MorphedByMany
*/
public function appusers()
{
return $this->morphedByMany(AppUser::class, 'taggable');
}
}