php - 用 withcount 和 orderby 分块巨大的查询
问题描述
我有一个非常繁重的查询,它达到了内存限制并返回 500 错误这里是查询:
$collection = User::with('city')
->withCount('userReferral')
->orderByDesc('user_referral_count')
->get();
$data = $collection->where('username', $userName);
这是一个排名,它根据她/他邀请到网站的用户数显示用户在用户排名上的排名。这现在在服务器上返回 500,这是因为内存限制,我不希望它消耗那么多内存。我如何用块重写它以减少内存消耗?
解决方案
您不应该使用集合的位置,而是直接使用 eloquent 运行它。
$collection = User::with('city')
->withCount('userReferral')
->orderByDesc('user_referral_count')
->where('username', $userName)
->get();
// Do something with your collection
如果您不需要一次所有用户,您也可以使用pagination。
$collection = User::with('city')
->withCount('userReferral')
->orderByDesc('user_referral_count')
->where('username', $userName)
->paginate(10);
推荐阅读
- r - 根据尖端标签着色的节点和尖端标签的系统发育比较
- oracle - 如何在提交页面前在选择列表中进行选择后清除文本框?
- javascript - 节点 - 如何从一个单词中删除 x 个字母
- javascript - Javascript总结对象中的不同值
- bison - 来自 sourceforge.net 的 win_bison.exe 是否恶意
- c# - 如何在 Json API 响应中删除值为 0 的字段
- php - Laravel 在邮件刀片文件外使用 $message->embed($image)
- mysql - 如何在 MySQL 5.7 中实现类似于“SKIP LOCKED”的功能?
- ruby-on-rails - 以最佳方式将字符串数组值转换为哈希
- docusignapi - 如何使用docusign api在php现有网站中集成docusign电子签名功能