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:

$sortedEntities = $repository->findBy(array('createdAt' => 'DESC'));

This is the attribute in question:

    /**
     * @var DateTime $createdAt
     *
     * @GedmoTimestampable(on="create")
     * @ORMColumn(type="datetime")
     */
    private $createdAt;

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

$tenUsers = $em->getRepository('MyProjectDomainUser')->findBy(array('age' => 20), array('name' => 'ASC'), 10, 0);

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

/**
 * Finds objects by a set of criteria.
 *
 * Optionally sorting and limiting details can be passed. An implementation may throw
 * an UnexpectedValueException if certain values of the sorting or limiting details are
 * not supported.
 *
 * @param array<string, mixed> $criteria
 * @param string[]|null        $orderBy
 * @param int|null             $limit
 * @param int|null             $offset
 * @psalm-param array<string, 'asc'|'desc'|'ASC'|'DESC'> $orderBy
 *
 * @return object[] The objects.
 * @psalm-return T[]
 *
 * @throws UnexpectedValueException
 */
public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null);

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:

sortedEntities = $repository->findBy(array(), array('createdAt' => 'DESC'));
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement