<?php

namespace Modules\User\Models;

use App\Models\Model;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Modules\User\Traits\BelongsToUser;

class Relation extends Model
{

    use BelongsToUser,
        ModelTree;

    protected $table = 'user_relations';

    protected $primaryKey = 'user_id';

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setParentColumn('parent_id');
        $this->setOrderColumn('created_at');
        $this->setTitleColumn('user_id');
    }

    /**
     * 上级用户
     *
     * @return BelongsTo
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(User::class, 'parent_id');
    }

    /**
     * Notes: 关联中间表
     *
     * @Author: 玄尘
     * @Date: 2022/8/19 13:16
     */
    public function identities(): BelongsToMany
    {
        return $this->belongsToMany(
            Identity::class,
            'user_identity',
            'user_id',
            'identity_id',
        );
    }


    /**
     * 所有下级用户
     *
     * @return HasManyThrough
     */
    public function children(): HasManyThrough
    {
        return $this->hasManyThrough(
            User::class,
            Relation::class,
            'parent_id',
            'id',
            'user_id',
            'user_id'
        );
    }

}
