Laravel 的 API 資源功能 whenLoaded()
可有條件地在 API 響應中包含關聯數據,通過防止不必要的數據庫查詢來優化性能。
以下是如何使用 whenLoaded()
方法的示例:
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class UserResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'posts' => PostResource::collection($this->whenLoaded('posts')) ]; } }
如果未加載“posts”關係,則 posts 鍵將從響應中移除,只留下“id”和“name”。
以下是在實際場景中如何使用它的示例:
<?php namespace App\Http\Controllers; use App\Models\Article; use App\Http\Resources\ArticleResource; use Illuminate\Http\Request; class ArticleController extends Controller { public function index(Request $request) { $query = Article::query(); if ($request->boolean('with_author')) { $query->with('author'); } if ($request->boolean('with_comments')) { $query->with(['comments' => fn($query) => $query->latest()]); } return ArticleResource::collection($query->paginate()); } } class ArticleResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'content' => $this->content, 'author' => new UserResource($this->whenLoaded('author')), 'comments' => CommentResource::collection( $this->whenLoaded('comments') ), 'latest_comment' => $this->whenLoaded('comments', function() { return new CommentResource($this->comments->first()); }) ]; } }
此實現通過以下方式演示了高效的關係處理:
使用 whenLoaded()
有助於創建精簡高效的 API,這些 API 可以在需要時優化數據庫查詢並保持包含相關數據的靈活性。
以上是Laravel負載 - 通過有條件關係加載的性能優化的詳細內容。更多資訊請關注PHP中文網其他相關文章!