优化 Laravel 中大型数据集的查询涉及多种提高性能和效率的策略。以下是您可以使用的一些关键技术:
高效使用口才 选择特定列:仅选择您需要的列,以最大程度地减少检索的数据量。1
$users = User::select(id, name, email)->get();
Eager Loading:使用Eager Loading来防止N+1查询问题。
1
$users = User::with(posts, comments)->get();
1
$users = User::paginate(50);
1
2
3
Schema::table(users, function (Blueprint $table) {
$表->索引(电子邮件);
});
1
2
3
4
5
1
2
3
$users = Cache::remember(active_users, 60, function () {
return User::where(status, active)->get();
});
1
2
3
4
5
DB::enableQueryLog();
// 运行您的查询
$users = User::all();
$queries = DB::getQueryLog();
dd($查询);
1
2
3
4
5
6
7
8
9
11
// 不好:N+1 问题
$users = User::all();
foreach ($users 作为 $user) {
echo $用户->个人资料->个人简介;
}
// 好:渴望加载
$users = User::with(profile)->get();
foreach ($users 作为 $user) {
echo $用户->个人资料->个人简介;
}
优化复杂查询
假设您需要获取用户的帖子和评论,并且您想优化此操作:
1
2
3
4
5
6
7
8
$users = User::select(id, 姓名, 电子邮件)
->with([posts => 函数 项目网点我wcqh.cn($query) {
$query->select(id, user_id, 标题)
->with([comments => function ($query) {
$query->select(id, post_id, 内容);
}]);
}])
->分页(50);
暂无评论内容