One way to get a random Doctrine entity

Code
<?php

use PHPSnippets\Db\Entity\Test;

$query = $entityManager->createQuery('SELECT MAX(t.id) FROM ' . Test::CLASS . ' t');
// count can be cached if value doesn't change regularly
$maxId = (int) $query->getSingleScalarResult();
$rand = rand(1, $maxId);

echo 'random id = ' . $rand . ' of max id = ' . $maxId . PHP_EOL;

// In theory, the table row of former max id could be deleted by another request at this point
$qb = $entityManager->createQueryBuilder();
$qb->select('t')
    ->from(Test::CLASS, 't')
    // greater or equal in case of deleted ids
    ->where($qb->expr()->gte('t.id', $rand))
    ->setMaxResults(1);
$entity = $qb->getQuery()->getSingleResult();

echo 'found: ' . $entity->id . ', ' . $entity->name;
Result
random id = 2 of max id = 3
found: 2, test
Used Versions
PHP 8.3, Laminas MVC 3.2, Symfony 5.2, Laravel 8.28, PHPUnit 9.5, Doctrine ORM 2.8