使用ContainerAwareCommand执行Query Doctrine

I have extends my class from ContainerAwareCommand. I have execute function and I want to execute a query. This is the execute function with my $em and my $repo.

 protected function execute(InputInterface $input, OutputInterface $output){
            $em = $this->getContainer()->get('doctrine')->getEntityManager();
            $repo = $em->getRepository('SshBundle:Cinema');

How can I now execute a query? Thanks.

You have several ways to make a query from this point.

  1. If you have a custom repository for the Cinema entity then you could create a method on the Cinema repository that returns the results that you want to get. Or you can use the find, findBy, findOneBy methods of the Repository class, eg.

    $current = $repo->find($current_id);

  2. You can use the Doctrine Query Language(DQL) to create a query using the entity_manager variable, in your case $em.

    $results = $em->createQuery("SELECT c FROM SshBundle:Cinema c")->getResult()

it will return an Entity Collection with the results that match your conditions.

  1. Using a Query Builder:

    $results = $em->createQueryBuilder()->select('c')->from('SshBundle:Cinema', 'c')->getQuery()->getResult()

It will do the same thing as (2).

  1. Using raw SQL queries mean the connection.

    $results = $em->getConnection()->fetchAll('SELECT * FROM your_table_name')

In 1 and 2 and 3 you can pass a parameter to the getResult function in order to establish the hydration mode of the results, to fetch the results as entities, objects or arrays.

Your queries can also return scalar results for example the COUNT ones. The entity manager has methods to handle them as well.

I hope this helps.