Laravel whenLoaded - 通过条件关系加载进行性能优化

2024 年 12 月 14 日

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,以优化数据库查询,同时保持在需要时包含相关数据的灵活性。


帖子 Laravel whenLoaded - 通过条件关系加载进行性能优化 首先出现在 Laravel 新闻

加入 Laravel 时事通讯 获取最新信息 类似这样的 Laravel 文章将直接发送到您的收件箱。