Переписав код таким вот образом проблема решилась
public function parseBrands()
{
$em = $this->em;
for ($iteration = 2637; $iteration < 3144; $iteration += 1) {
$category = $em->getRepository('MainCatalogBundle:Categories')->findOneBy(
array(
'id' => $iteration,
)
);
if ($category) {
echo $category->getId();
foreach ($category->getProducts() as $product) {
$brandId = $product->getBrand()->getId();
$brand = $em->getRepository('MainCatalogBundle:Brand')->findOneBy(
array(
'id' => $brandId,
)
);
if (!$brand || $category->getBrands()->contains($brand)) {
break;
}
$category->getBrands()->add($brand);
$brand->getCategories()->add($category);
$em->flush();
}
$em->clear();
}
}
}