我是Symfony的新手。我创建了一个自定义命令,其唯一目的是擦除系统中的演示数据,但是我不知道该怎么做。

在 Controller 中,我将执行以下操作:

$nodes = $this->getDoctrine()
    ->getRepository('MyFreelancerPortfolioBundle:TreeNode')
    ->findAll();

$em = $this->getDoctrine()->getManager();
foreach($nodes as $node)
{
    $em->remove($node);
}
$em->flush();

从我得到的命令中的execute()函数执行此操作:
Call to undefined method ..... ::getDoctrine();

我将如何从execute()函数执行此操作?另外,如果除了擦除数据和循环删除数据之外,还有一种更简便的擦除数据的方法,请随时提及。

最佳答案

为了能够访问服务容器,您的命令需要扩展Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand

请参见命令文档章节Getting Services from the Container

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
// ... other use statements

class MyCommand extends ContainerAwareCommand
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine')->getEntityManager();
        // ...

09-10 10:23
查看更多