Sid Sid - 24 days ago 6x
PHP Question

Why isn't count returning the correct number of elements in a Doctrine Collection?

I have the following code:

$em = $this->getDoctrine()->getManager();
if($groupType == 'existing'){
$urlGroup = $em->getRepository('UrlBuilderBundle:UrlGroup')->find($groupId);
}elseif($groupType == 'new'){
$urlGroup = new UrlGroup();
$groupName = $submittedData['groupName'];

$url = new Url();


$urlGroupName = $urlGroup->getName();
$urlCount = count($urlGroup->getUrls());

When a new UrlGroup is created, the last line (count of child URL objects) always returns zero even when a URL has been added for the given UrlGroup. This code is used in an AJAX call.

Upon page refresh count() returns the correct number.

Appreciate it if anyone can help shed some light on the issue.


This is because fact that you do $em->flush() means that database operation is performed but it does not mean that your $urlGroup object is refreshed - php still has its state before flush has been performed, meaning with 0 urls.

Try to call:


right after $em->flush. This will refresh $urlGroup with info from database