ホームページ >バックエンド開発 >PHPチュートリアル >LARAVEL -LOADED-条件付き関係の負荷によるパフォーマンスの最適化
は、API応答に関連するデータを条件付きで含めることができます。不必要なデータベースクエリを防ぐことでパフォーマンスを最適化できます。 whenLoaded()
次のことは、
メソッドの使用方法の例です。
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')) ]; } }
以下は、実際のシナリオでそれを使用する方法の例です。
この実装は、次のような効率的な関係処理を示しています要求パラメーターに基づく
動的関係のロード<?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()); }) ]; } }を含む条件付き パフォーマンスを改善するための最適化されたクエリ読み込み
以上がLARAVEL -LOADED-条件付き関係の負荷によるパフォーマンスの最適化の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。