为什么remove()认为我的实体是一个数组

时间:2016-05-23 11:36:52

标签: symfony doctrine-orm

为什么Symfony不会将我的实体视为实体?正如在#2中看到的那样,Symfony知道这个类,并且教条应该也可以找到新闻实体。

 /**
 * 
 * @Route("/news/delete/{id}", name="news_delete")
 */
public function deleteAction($id) {

    $toDelete = new News();

    $em = $this->getDoctrine()->getManagers();

    $toDelete = $this->getDoctrine()
                ->getRepository('AppBundle:News')
                ->findOneBy(array('id' => $id));

    dump($toDelete); //Posted under #1
    dump(get_class($toDelete)); //Posted under #2
    $em->remove($toDelete);
    $em->flush();

    return $this->redirectToRoute('news_show', array(), 301);
}



#1:   
News {#926 ▼
      -id: 16
      +headline: "1313"
      +newsBody: "12313"
      +date: DateTime {#1027 ▶}
      +archiveDate: DateTime {#921 ▶}
      -categories: PersistentCollection {#934 ▶}
    }

#2:
"AppBundle\Entity\News"

修改 错误:调用数组

上的成员函数remove()

2 个答案:

答案 0 :(得分:1)

在办公室,有人向我指出我调用了getManagers()函数,该函数返回一个包含所有管理器的数组。

为了清楚起见,我还建议其余的代码。

 $em = $this->getDoctrine()->getManager();
    $repo = $em->getRepository('AppBundle:News');
    $toDelete = $repo->findOneBy(array('id' => $id));

感谢所有花时间开始处理我的问题的人。

答案 1 :(得分:1)

正如提示一样,您可以使用find()函数来避免魔术调用,因为您只使用了id

$toDelete = $this->getDoctrine()
            ->getRepository('AppBundle:News')
            ->find($id);

此外,我也遇到了问题,并使用instanceof

解决了这个问题
if($toDelete instanceof News)
{
    $em->remove($toDelete);
    $em->flush();
}