使用ContainerwareCommand执行查询原则


Execute Query Doctrine using ContainerAwareCommand

我已经从ContainerwareCommand扩展了我的类。我有execute函数,我想执行一个查询。这是我的$em和$repo的execute函数。

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

现在如何执行查询?谢谢

您有几种方法可以从这一点进行查询。

  1. 如果你有一个Cinema实体的自定义存储库,那么你可以在Cinema存储库上创建一个方法,返回你想要得到的结果。或者,您可以使用Repository类的find、findBy、findOneBy方法,例如

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

  2. 您可以使用条令查询语言(DQL)使用entity_manager变量创建查询,在您的情况下为$em。

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

它将返回一个实体集合,其中包含符合您条件的结果。

  1. 使用查询生成器:

    $results=$em->createQueryBuilder()->select('c')->from('shBundle:Chinema','c'])->getQuery()->getResult()

它将做与(2)相同的事情。

  1. 使用原始SQL查询意味着连接。

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

在1、2和3中,您可以向getResult函数传递一个参数,以便建立结果的水合模式,以实体、对象或数组的形式获取结果。

查询还可以返回标量结果,例如COUNT结果。实体管理器也有处理它们的方法。

我希望这能有所帮助。