
在 laravel 开发中,eloquent orm 极大地简化了数据库交互。然而,不当的查询构造方式,尤其是在处理关联数据和聚合操作时,可能导致性能瓶颈。一个常见的场景是,我们需要统计关联模型的数量,并根据这些数量进行排序,例如,统计用户发布的图片数量并生成排行榜。当查询逻辑中存在冗余或重复的条件判断时,数据库查询时间会显著增加,影响用户体验。
考虑以下一个典型的场景,我们需要查询在当前周、上周以及总榜上发布图片最多的用户:
public function show()
{
// 查询当前周发布图片最多的用户
$currentWeek = User::whereHas('pictures')
->whereHas('pictures', fn ($q) => $q->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()]))
->withCount(['pictures' => fn ($q) => $q->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])])
->orderBy('pictures_count', 'DESC')
->limit(10)
->get();
// 查询上周发布图片最多的用户
$lastWeek = User::whereHas('pictures')
->whereHas('pictures', fn ($q) => $q->whereBetween('created_at', [now()->startOfWeek()->subWeek(), now()->endOfWeek()->subWeek()]))
->withCount(['pictures' => fn ($q) => $q->whereBetween('created_at', [now()->startOfWeek()->subWeek(), now()->endOfWeek()->subWeek()])])
->orderBy('pictures_count', 'DESC')
->limit(10)
->get();
// 查询总榜发布图片最多的用户
$overall = User::whereHas('pictures')
->whereHas('pictures')
->withCount('pictures')
->orderBy('pictures_count', 'DESC')
->limit(10)
->get();
return view('users.leaderboard', [
'currentWeek' => $currentWeek,
'lastWeek' => $lastWeek,
'overall' => $overall,
]);
}上述代码在执行时可能耗时较长(例如 1.5 秒),主要原因在于其生成的 SQL 语句中包含了冗余的 EXISTS 子句,导致数据库需要执行不必要的检查。
在上述原始查询中,以 $currentWeek 为例,我们注意到 whereHas('pictures') 被调用了两次:一次是无条件的,另一次是带有时间范围条件的。
whereHas('pictures') 的作用是确保用户至少拥有一张图片。而 whereHas('pictures', fn ($q) => $q->whereBetween(...)) 则进一步确保用户在指定时间范围内拥有图片。显然,如果用户在指定时间范围内有图片,那么他们也必然有图片。因此,无条件的 whereHas('pictures') 是多余的。
优化前生成的 SQL 片段(针对 currentWeek):
-- ...
where exists (select * from `pictures` where `users`.`id` = `pictures`.`user_id` and `pictures`.`deleted_at` is null)
and exists (select * from `pictures` where `users`.`id` = `pictures`.`user_id` and `created_at` between ? and ? and `pictures`.`deleted_at` is null)
-- ...优化代码:
我们移除冗余的 whereHas('pictures') 调用:
$currentWeek = User::whereHas('pictures', fn ($q) => $q->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()]))
->withCount(['pictures' => fn ($q) => $q->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])])
->orderBy('pictures_count', 'DESC')
->limit(10)
->get();优化后生成的 SQL 片段:
-- ...
where exists (select * from `pictures` where `users`.`id` = `pictures`.`user_id` and `created_at` between ? and ? and `pictures`.`deleted_at` is null)
-- 注意:不再有第二个 where exists 子句
-- ...通过这一步,我们减少了一个 EXISTS 子句,使得 SQL 查询更简洁,性能有所提升。
进一步分析,我们发现 $currentWeek 查询中 whereHas 的条件与 withCount 的条件是完全相同的。
关键在于,如果一个用户在指定时间范围内没有图片,那么 withCount 会返回 0。由于我们最终是按照 pictures_count 降序排序并取前 10 名,那些计数为 0 的用户自然会排在后面,或者根本不会进入前 10 名。这意味着,whereHas 的存在性检查在这里变得多余。withCount 已经包含了筛选和计数的功能,whereHas 只是在重复其作用。
优化代码:
我们可以完全移除 whereHas 调用,只保留 withCount:
$currentWeek = User::withCount(['pictures' => fn ($q) => $q->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])])
->orderBy('pictures_count', 'DESC')
->limit(10)
->get();优化后生成的 SQL 片段:
select `users`.*, (
select count(*) from `pictures` where `users`.`id` = `pictures`.`user_id` and `created_at` between ? and ? and `pictures`.`deleted_at` is null
) as `pictures_count`
from `users`
where `users`.`deleted_at` is null
-- 注意:不再有任何 where exists 子句
order by `pictures_count` desc
limit 10通过这一最终优化,我们完全消除了 EXISTS 子句,使得 SQL 查询变得极其高效。数据库不再需要执行额外的存在性检查,只需计算每个用户的图片数量并进行排序。
对数据结果的影响及处理:
这种优化可能会导致返回的集合中包含 pictures_count 为 0 的用户(如果这些用户在排序后仍然进入了前 10 名)。如果你的排行榜不希望显示计数为 0 的用户,可以在获取结果后进行过滤:
$currentWeek = User::withCount(['pictures' => fn ($q) => $q->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])])
->orderBy('pictures_count', 'DESC')
->limit(10)
->get()
->filter(fn ($user) => $user->pictures_count > 0); // 过滤掉计数为0的用户对于 overall 查询的优化:
同样的原理也适用于 overall 查询。原始的 overall 查询:
$overall = User::whereHas('pictures')
->whereHas('pictures') // 冗余
->withCount('pictures')
->orderBy('pictures_count', 'DESC')
->limit(10)
->get();优化后可以简化为:
$overall = User::withCount('pictures')
->orderBy('pictures_count', 'DESC')
->limit(10)
->get();因为 withCount('pictures') 会计算所有图片,如果用户没有图片,计数为 0,自然会排在后面。
本次优化案例揭示了 Eloquent 查询性能提升的关键原则:
通过遵循这些最佳实践,你将能够编写出更高效、更具可维护性的 Eloquent 查询,显著提升 Laravel 应用的整体性能。
以上就是Eloquent 查询优化:提升关联计数与排序性能的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号