<?php

namespace App\Models;



use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;

class SiteAlbumFolder extends Model
{
    protected $table = 'site_album_folder';

    // 定义与自身的关系，用于获取子文件夹
    public function children()
    {
        return $this->hasMany(SiteAlbumFolder::class, 'parent_id');
    }

    // 递归构建父子关系树
    public static function buildTree(Collection $folders, $parentId = null)
    {
        return $folders
            ->where('parent_id', $parentId) // 过滤出当前层级的文件夹
            ->map(function ($folder) use ($folders) {
                // 递归获取子文件夹
                $folder->children = self::buildTree($folders, $folder->id);
                return [
                    'id' => $folder->id,
                    'title' => $folder->title,
                    'parent_id' => $folder->parent_id,
                    'order' => $folder->order,
                    'folder_type' => $folder->folder_type,
                    'show_tabs' => $folder->show_tabs,
                    'enabled' => $folder->enabled,
                    'created_at' => $folder->created_at,
                    'updated_at' => $folder->updated_at,
                    'cover' => $folder->cover,
                    'children' => $folder->children->values()->toArray(), // 子文件夹数据
                ];
            })
            ->values(); // 重置键名
    }

}
