简体   繁体   English

Symfony 2删除具有oneToMany关系的实体

[英]Symfony 2 deleting entity with a oneToMany relationship

In my Gecko.php i have the following part: 在我的Gecko.php我有以下部分:

    /**
     * @ORM\OneToMany(targetEntity="Weight", mappedBy="geckoId")
    */
    private $weights;

And in my Weight.php i have this: 在我的Weight.php我有这个:

/**
 * @ORM\ManyToOne(targetEntity="Gecko", inversedBy="weights")
 * @ORM\JoinColumn(name="gecko_id", referencedColumnName="id")
 */
private $geckoId;

My gecko delete action is as follows: 我的壁虎删除操作如下:

/**
 * Deletes a Gecko entity.
 *
 * @Route("/{name}", name="gecko_delete")
 * @Method("DELETE")
 */
public function deleteAction(Request $request, $name)
{
    $form = $this->createDeleteForm($name);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('BreedrGeckoBundle:Gecko')->findOneByName($name);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Gecko entity.');
        }

        $em->remove($entity);
        $em->flush();
    }

    return $this->redirect($this->generateUrl('gecko'));
}

When i click the delete button in my form, i get this error: 当我单击表单中的删除按钮时,出现此错误:

An exception occurred while executing 'DELETE FROM Gecko WHERE id = ?' 执行“从Gecko WHERE id =?删除”时发生异常。 with params [5]: 带有参数[5]:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails ( breedr . weight , CONSTRAINT FK_615077FC45D556 FOREIGN KEY ( gecko_id ) REFERENCES Gecko ( id )) SQLSTATE [23000]:完整性约束违规:1451无法删除或更新父行,外键约束失败( breedrweight ,约束FK_615077FC45D556外键( gecko_id )参考文献Geckoid ))

I don't know how to fix this issue. 我不知道如何解决此问题。 When there are no weights in the database for a specific gecko, they delete fine, but if there are any weights, it won't delete. 当数据库中没有特定壁虎的权重时,它们会被删除,但是如果有任何权重,则不会删除。 Ideally i would like to be able to delete all weight data at the same time that a gecko is deleted 理想情况下,我希望能够在删除壁虎的同时删除所有体重数据

Thanks in advance 提前致谢

Andy 安迪

If you don't manually remove the owned entities of a parent entity before deleting it, you'll get errors like this. 如果在删除父级实体之前没有手动删除其拥有的实体,则会出现类似的错误。 You can either loop through all the owned entities and delete them manually before deleting the parent, or you can set Doctrine to automatically cascade delete operations: 您可以遍历所有拥有的实体并在删除父实体之前手动将其删除,也可以将Doctrine设置为自动级联删除操作:

Doctrine Cascade Operations 学说级联运算

/**
 * @ORM\OneToMany(targetEntity="Weight", mappedBy="geckoId", cascade={"persist", "remove"})
*/
private $weights;

Add cascade operations to weights, so whenever Gecko will be updated or deleted, the weights related to it will also be updated / removed. 向权重添加级联操作,因此每当壁虎被更新或删除时,与其相关的权重也将被更新/删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM