資料庫結構
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 協議》,轉載必須註明作者和本文連結