首页 > 解决方案 > 用 withcount 和 orderby 分块巨大的查询

问题描述

我有一个非常繁重的查询,它达到了内存限制并返回 500 错误这里是查询:

       $collection = User::with('city')
            ->withCount('userReferral')
            ->orderByDesc('user_referral_count')
            ->get();

        $data  = $collection->where('username', $userName);

这是一个排名,它根据她/他邀请到网站的用户数显示用户在用户排名上的排名。这现在在服务器上返回 500,这是因为内存限制,我不希望它消耗那么多内存。我如何用块重写它以减少内存消耗?

标签: phpmysqllaravel

解决方案


您不应该使用集合的位置,而是直接使用 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);

推荐阅读