Search code examples
ormpropel

How do I order the results of a 1 to many relationship


I'm using Propel 1.5.7 and can't figure out the right way to order the results of a get[Related]s() call.

e.g.

Say, an Author has many Books:

 $leo = AuthorQuery::create()->findByLastName("Tolstoy");
 $books = $leo->getBooks();

And, books have a PublishDate column.

How do I get $books to be sorted by PublishDate? Can I pass something to getBooks() to make this happen. I can't find any mention of it in the docs.


Solution

  • In my knowledge, this is the only way to sort leo's books by publication date.

    You can however make it prettier by using the BookQuery class to create your criteria (as a BookQuery is indirectly a Criteria) :

    $criteria = BookQuery::create()->orderByPublishDate();
    $books = $leo->getBooks($criteria);
    

    Using this method, you'll also be able to use the methods defined in your BookQuery class and, let's imagine, only retrieve five leo's books published by a given author.

    $criteria = BookQuery::create()
        ->filterByGenre('Fiction');
        ->limit(5);
        ->orderByPublishDate();
    $books = $leo->getBooks($criteria);