如何在Laravel中实现按关注者计数对用户列表进行排序的功能


How to implement a feature that sorts a users list by followers count in Laravel?

需要一些建议。我们在我们的应用程序中添加了一个跟随功能。我们使用本教程的模型和表结构- http://ilikekillnerds.com/2014/09/how-to-create-a-user-followingfollower-system-like-twitter-in-laravel-4/

我们添加了一个后续页面,该页面基本上列出了用户关注的用户的用户名。现在的问题是,我们需要添加一个功能排序的追随者计数列表。你能想到的添加该功能的最简单方法是什么?如果可能的话,不要缓存(比如在用户表中存储追随者计数),并且仍然可以使Laravel的->paginate()功能正常工作。只有当使用一个简单的Eloquent查询无法实现时,我才希望使用缓存。

我已经想不出如何为它构造Eloquent查询了。

我们使用的是Laravel 5.1。

提前感谢!:)

您想要根据其计数显示以下列表。

$topUsersJoinQuery = DB::table('user_follows')
            ->select('follow_id', DB::raw('COUNT(follow_id) AS count'))
            ->groupBy('follow_id'); //this will fetch the followers ids and group them.
$top_users = DB::table('users')->select('*')
            ->join(DB::raw('(' . $topUsersJoinQuery->toSql() . ') i'), function ($join)
            {
                $join->on('i.follow_id', '=', 'users.id');
            })
            ->orderBy('count', 'desc')
            ->select('name','id','title')
            ->take(3)
            ->get(); //joining the user_follows table with users table to fetech users info for view.blade.php

希望对你有帮助。

如何使用这样的查询:

select 
users.*, followerTempTable.followers_count 
from users 
left join (
    select user_id, count(*) as followers_count from followers group by user_id
) as followerTempTable on followerTempTable.user_id = users.id 
order by followers_count
-- add your limit and offset conditions for pagination

这个链接可能也有用:http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/