【发布时间】:2016-01-04 02:35:33
【问题描述】:
我有一个具有一对多关系的用户和推荐表。我正在尝试根据与其他用户相比的推荐计数来获得用户的排名。我只能根据他们的推荐数量列出用户。
$users = App\User::with('referrals')->get()->sortBy(function($user)
{return $user->referrals->count();});
但我不知道如何获得排名或根据推荐次数对行进行排序。
这是我的推荐表:
Schema::create('referrals',function(Blueprint $table){
$table->increments('id');
$table->bigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->bigInteger('referral_id');
$table->timestamps();
});
例如,如果我的数据库中有这个
user id 1 | 5 referrals
user id 2 | 10 referrals
user id 3 | 1 referral
我希望能够得到用户 id 2 的排名,也就是 1。
【问题讨论】:
-
由于您已经有排序数组,您知道该数组中的第一个用户拥有最多的推荐。所以他们将有排名 1。这不是很简单吗?你还需要什么?
-
我需要排名#,表明该用户与其他用户相比拥有最多。我在用户个人资料中显示了这一点。所以像 user-> rank = ?但我不想创建排名列。我想根据排序获得特定用户的排名。希望这是有道理的。
标签: php mysql laravel laravel-5 eloquent