<?php

namespace App\Game;

use App\Game\Services\RouteService;
use Illuminate\Database\Eloquent\Model;

class RouteModel extends Model
{
    protected $connection='mysql';

    const TABLE = 'webgame.routes';
    protected $table = self::TABLE;

    protected $fillable = [
        'path', 'type', 'side', 'block', 'title', 'icon',
        'fill', 'component', 'query', 'login', 'lpath', 'subs'
    ];

    // 由于subs是嵌套的，可能需要特别处理或使用访问器
    protected $casts = [
        'subs' => 'array'
    ];
    // 子路由关系
    public function subs()
    {
        return $this->hasMany(RouteModel::class, 'parent_id', 'id')->whereRaw(RouteService::getStateToWhereRaw())->orderBy('index');
    }

    // 父路由关系，可选，如果你需要从子路由访问父路由
    public function parent()
    {
        return $this->belongsTo(RouteModel::class, 'parent_id', 'id');
    }
    public function getSubsAttribute($value)
    {
        return array_map(function ($sub) {
            return new self($sub);
        }, json_decode($value, true));
    }

    public function setSubsAttribute($value)
    {
        $this->attributes['subs'] = json_encode($value);
    }
}

