<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

trait SelfReferenceTraits
{
    protected string $parentColumn = 'parent_id';

    public function parent(): BelongsTo
    {
        return $this->belongsTo(static::class);
    }

    public function children(): HasMany
    {
        return $this->hasMany(static::class, $this->parentColumn);
    }

    /*
     * same level items
     */
    public function allChildren()
    {
        return $this->children()->with('allChildren');
    }

    /*
     * not working!!
     */
    public function root()
    {
        return $this->parent ? $this->parent->root() : $this;
    }
}
