Q:

doctrine 2 cascade persist saving too much

so this is my prePersist on EventListener
public function prePersist(LifecycleEventArgs $args)
    {
        //the first entity will have the PMP, so we catch it and continue to skip this if after this
        if ($this->pmp == null) {
            $this->pmp = $args->getEntity()->getPmp();
        }

        $taxonomicClass = $args->getEntity();

        if($taxonomicClass instanceof TaxonomicClass){

            if(is_null($taxonomicClass->getId())){
                //here it says that i have created a new entity, need to persist it via cascade={"persist"}
                $taxonomicClass->setPmp($this->pmp);
            }
        }
    }

that's fine, i had added the annotation on it:
 /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Pmp", cascade={"persist"})
     * @ORM\JoinColumn(name="pmp_id", referencedColumnName="id", nullable=false)
     **/
    private $pmp;

and it saves everything from my hierarchy, even a new PMP, an object that already exist in the database!
what i want is that everything that im saving from my hierarchy needs to be related to the PMP that i passed, but when i set $taxonomicClass->setPmp($this->pmp); doctrine thinks that i created a new instance of PMP, since im not, i just want to this guy have an associaton with the PMP.
i tried put merge on the cascade option, but it only works with persist, how to make doctrine dont create a new instance, and instead use the one that i passed?

A:

noticed my problem, i was assigning an attribute from memory, i should retrive him from database to doctrine understand.
public function prePersist(LifecycleEventArgs $args)
{
    if ($this->pmp == null) {
            $this->pmp = $args->getEntity()->getPmp();
    }

    $taxonomicClass = $args->getEntity();

    if($taxonomicClass instanceof TaxonomicClass){

        if(is_null($taxonomicClass->getId())){
            //this solved the problem
            $pmp = $args->getEntityManager()->getRepository("AppBundle:Pmp")->find($this->pmp->getId());
            $taxonomicClass->setPmp($pmp);
        }
    }
}

i will keep in mind now that when a new entity is created, but it doesn't need to be saved, you must retrieve it from db, cascade={"persist"} wasn't even necessary

