Search code examples
phpmysqlsqlpropel

Get last 5 item of sql results with Propel


I want to get the last 5 items of my search action. An example:

$quizzes = $user->getQuizs();

Now I would like to select the last 5 of that, is this possible with propel?
I tried ->getLast(5) but that's not correct.

Let's say I get 30 quizzes back, ordered by ID. I want to select the last 5 (with the highest id's .., these are the ones last created).


Solution

  • Easy peasy:

    $quizzes = QuizQuery::create()->
        filterByUser($user)->
        orderByCreatedAt(\Criteria::DESC)->
        limit(5)->
        find()
    ;
    

    This assumes you have a created_at column in your quiz table. You can then add this to your User model if you wish:

    public function getLastQuizzes($limit = 5)
    {
        return QuizQuery::create()->
            filterByUser($this)->
            orderByCreatedAt(\Criteria::DESC)->
            limit($limit)->
            find()
        ;
    }