記一次通過 Resource 遞迴生成樹的方案

sureyee發表於2019-10-29

資料庫結構

記一次通過Resource遞迴生成樹的方案

Model:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Menu extend Model {
    protected $table = 'menus';
    protected $fillable = ['name'];
    public function children()
    {
        return $this->hasMany(Menu::class, 'parent_id');
    }
    public function scopeParents($query)
    {
        return $query->where('depth', 0);
    }
}

Resource:

namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class TreeResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'parentId' => $this->parent_id,
            'name' => $this->name,
            'children' => TreeResource::collection(
                $this->children->load(['children' => function ($query) {
                    return $query->orderBy('sorter', 'asc');
                }])
            ),
        ];
    }
}

Controller:

namespace App\Http\Controllers;
use App\Http\Resources\TreeResource;
use App\Menu;
use Illuminate\Http\Request;
class StoreGroupController extends Controller
{
    public function tree()
    {
        $parents = Menu::with([
            'children' => function ($query) {
                return $query->orderBy('sorter', 'asc'); // 排序
            }])->parents()->orderBy('sorter', 'asc')->get();
        return TreeResource::collection($parents);
    }
}

採用load()減少每次遞迴時候的查詢量

可在閉包中新增排序規則

本作品採用《CC 協議》,轉載必須註明作者和本文連結

打醬油

相關文章