biera
biera

Reputation: 2667

Doctrine2 PostPersist: updating corresponding entity

I have two entities (note that irrelevant methods and properties are omitted):

/**
* @Entity
*/
class Manager {

   /**
    * @Column(type="integer")
    */
    private $referencesCount;

    /**
    * @OneToMany(targetEntity="Reference", mappedBy="manager")
    */
    private $references;

    public functions increaseReferenceCount() {
        $this->referencesCount++;
    }

     // other properties and methods
}


/**
* @Entity
* @HasLifecycleCallbacks
*/
class Reference {

    /**
    * @ManyToOne(targetEntity="Manager", inversedBy="references")
    * @JoinColumn(nullable=false)
    */
    private $manager;

    /**
    * @PostPersist
    */
    public function updateManagerReferenceCount() {
        $this->manager->increaseReferenceCount()
    }

     // other properties and methods
}

Manager can have many References. One Reference belongs exactly to one Manager. My model should be optimized for queries, so to avoid expensive joins (Manager has much more associations) I add to Manager model $referencesCount property which, you guessed it, holds the numbers of its references. After new Reference is persisted, $referencesCount should be increased. But right now it is not. What am I missing? (I already tired wit cascade={"all"} but it does not work for me)

Upvotes: 0

Views: 491

Answers (1)

Athlan
Athlan

Reputation: 6619

You should add Transitive persistence

cascade={"all"}

to Reference entity (not only for Manager).

And replace @PostPersist to @PrePersist.

Upvotes: 2

Related Questions