Skip to content
Advertisement

Symfony 5 / Doctrine: Sorting entity collection by creation DateTime

I am developing a project using Symfony 5. One of my use-cases involves reading a collection from the Database, with the items sorted by creation order, descending (newest first). I am using the “Timestampable” extension from “stof/doctrine-extensions-bundle” to save the createdAt and updatedAt timestamps in my entity.

According to Doctrine documentation, I can sort items ussing the Repository methods:

JavaScript

This is the attribute in question:

JavaScript

However, using ‘ASC’ or ‘DESC’ seems to have no impact on the ordering of the list.

Advertisement

Answer

You are not reading the documentation correctly. The orderBy is the second argument, not the first. The example given in the docs is

JavaScript

Here, you can see the orderBy (name, ASC) is the second arg. The first arg is a where arg – in this case, WHERE age = 20.

Here is the full signature from DoctrinePersistenceObjectRepository

JavaScript

I hope that clarifies it for you. 🙂

[EDIT] In response to your comment, you cannot use true as a value for the first argument. Look at the signature I posted. The first argument is @param array<string, mixed>, so it needs an array. Try this then:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement