Search code examples
symfonyconsoledoctrineflush

Symfony 2.8: Calling $em->flush() from command


I try to flush my updated objects to the database but for some rease i get this error:

Attempted to call an undefined method named "flush" of class "Doctrine\Bundle\DoctrineBundle\Registry".

this is how my command looks

<?php
// src/AppBundle/Command/CheckHoseCondition.php
namespace AppBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Console\Helper\ProgressBar;
use \DateTime;

class CheckHoseConditionCommand extends ContainerAwareCommand
{

    protected function configure()
    {
         // ...
    }


    protected function execute(InputInterface $input, OutputInterface $output)
    {

        // connect to doctrine
        $em = $this->getContainer()->get('doctrine');

        // fetch all userHoses objects
        $userHoses = $em->getRepository('AppBundle:UserHose')->findAll();

        // check dates
        $today = new DateTime(); // vandaag
        $almostExpiredDate = new DateTime('+3 months');

        foreach($userHoses as $hose)
        {

            // change condition to 2
            if ( ($today > $hose->getExpirationDate()) && ($hose->getExpirationDate() != NULL) )
            {

                $hose->setHosecondition(2);

            }

            // change condition to 1
            if ( ($today <= $hose->getExpirationDate()) && ($almostExpiredDate >= $hose->getExpirationDate()) && ($hose->getExpirationDate() != NULL) )
            {

                $hose->setHoseCondition(1);

            }

        }

        // flush the updated objects
        $em->flush();

    }
}

Thanks in advance.


Solution

  • You forgot to call getManager()

    like that :

    $em = $this->getContainer()->get('doctrine')->getManager();