首页 > 后端开发 > php教程 > Laravel负载 - 通过有条件关系加载的性能优化

Laravel负载 - 通过有条件关系加载的性能优化

Robert Michael Kim
发布: 2025-03-06 02:03:08
原创
912 人浏览过

Laravel whenLoaded - Performance Optimization via Conditional Relationship Loading

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

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板