doctrine / orm

Doctrine Object Relational Mapper (ORM)
https://www.doctrine-project.org/projects/orm.html
MIT License
9.86k stars 2.5k forks source link

A cycle has been detected, so a topological sort is not possible. The getCycle() method provides the list of nodes that form the cycle. #11437

Closed collmomo closed 1 month ago

collmomo commented 1 month ago

Bug Report

Q A
BC Break yes/no
Version 3.1.3

Summary

The following message get thrown: "A cycle has been detected, so a topological sort is not possible. The getCycle() method provides the list of nodes that form the cycle." after removing/flushing an entity while using semantically correct doctrine syntax and sound logic

Current behavior

Blocking the flush process from removing the entity while using OneToOne relations. More context here: Stackoverflow

How to reproduce

OneToOne relations with self using cascade:remove

class Parent {

 #[ORM\OneToMany(targetEntity: PageTemplate::class, cascade: ['persist', 'remove'])] 
    private Collection $pageTemplates;

}

class PageTemplate {

    // ====================== PREVIOUS/NEXT ================================ //

    #[ORM\OneToOne(targetEntity: self::class, cascade: ['persist', 'remove'])]
    private ?self $nextPage= null;

    #[ORM\OneToOne(targetEntity: self::class, cascade: ['persist', 'remove'])]
    private ?self $previousPage = null;`
}

$em->remove($parent);
$em->flush();

Expected behavior

Don't throw the error, there's no cycle (infinite loop?) here, just remove the entity.

I fixed the issue by adding the following attribute: #[ORM\JoinColumn(nullable: true, onDelete: 'CASCADE')]

Another solution could have been to manually clear the relations before removing the entity:

    #[ORM\PreRemove]
    public function onPreRemove(PreRemoveEventArgs $args): void {
        /* Remove any references to self, as this will throw a CycleDetectedException */
        foreach ($this->getPageTemplates() as $pageTemplate):
            $pageTemplate->setNextPage(null);
            $pageTemplate->setPreviousPage(null);
        endforeach;
    }