Reputation: 1135
There is probably some easy way to do this, but I have thought about it for a while and searched and can't seem to find an answer. I am basically trying to limit the results, but include more than the limit if the proceeding rows past the limit are the same. For example:
Name Score
John 5
Mike 4
Lucy 3
Sara 3
Thea 2
If I wanted to limit the results I would do something like:
$topthree = Users::orderBy('score','desc')->limit(3)->get();
This would get me the top three results, but how would I also include Sara(from example data), since she also is in the top three scores?
I have considered returning more than I need and doing additional filtering, but I assume there is a better way. Any help is appreciated!
Upvotes: 1
Views: 207
Reputation: 31802
You can try using two queries.
First get the 3rd place score:
$minScore = Users::orderBy('score','desc')->skip(2)->take(1)->value('score');
Then get get all users with at least that score:
$topthree = Users::orderBy('score','desc')->where('score', '>=', $minScore)->get();
That might also work with a subquery:
$minScoreQuery = Users::select('score')->orderBy('score','desc')->skip(2)->take(1);
$topthree = Users::orderBy('score','desc')
->where('score', '>=', $minScoreQuery)
->get();
Upvotes: 1