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中文网其他相关文章!