Row Number in Symfony Doctrine Query
I am storing data for lap times in a database, the data consists of a distance, time, average speed and max speed.
I am trying to display a leaderboard which shows the top ten people in whatever query you set (who has gone thr furthest in total, best average time etc). However, below the top ten I want to show the user who is logged ins position in the leaderboard. To do this I am trying to run the same query ordering my results and adding a ROW NUMBER to get the position.
I am using symfony 1.4 with the Doctrine ORM and I can't for the life of me figure out how to get row numbers in a query. I know you can do it in SQL like so:
SELECT full_name, ROW_NUMBER() OVER(ORDER BY distance) AS row_number
Yet I can't get it working in Doctrine Symfony.
Does anyone 开发者_StackOverflow中文版have any ideas on a way I can do this? (or even another way of going about it)
Thanks in advance.
Ok heres my solution:
I kind of found an answer to this after some more experimenting and collaborating.
What I did was get rid of the select and just return the ordered list of results;
$results = self::getInstance()->createQuery('r')
->orderBy('r.distance')
->execute();
Then I hydrated this result into an array and used array_search() to find the key of the result in the array (luckily I am returning user data here, and I know the user I am looking for in the array)
$index = array_search($user->toArray(), $results->toArray());
I can then return the $index + 1 to give me the users position in the leaderboard.
There is probably a better way to do this database side, but I couldn't for the life of me find out how.
If anyone has a better solution then please share.
精彩评论