2013-03-23 36 views
0

我有两个实体(注意,不相关的方法和属性被省略):Doctrine2 PostPersist:更新相应的实体

/** 
* @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模型$ referencesCount属性中,您猜对了它,它保存了引用的数量。在新引用持久之后,应该增加$ referencesCount。但现在不是。我错过了什么? (我已经厌倦了机智级联= { “所有”},但它不为我工作)

+0

也许你忘了在更改属性后忘记坚持经理实体,是吗? – lazyhammer 2013-03-23 14:24:45

+0

错别字? '@ H​​asLifecycleCallbacs' vs'@ HasLifecycleCallbacks' – Crisp 2013-03-23 15:18:28

+0

@Crisp - 不,这不是一个错字:) – biera 2013-03-23 17:14:11

回答

2

您应该添加Transitive persistence

cascade={"all"}

Reference实体(不仅为Manager)。

并将@PostPersist替换为@PrePersist

+0

我在引用中的ManyToOne和管理器中的OneToMany中添加了Cascade = {“all”} - 它没有像我期望的那样工作。 – biera 2013-03-23 17:13:40

+0

尝试将'@ PostPersist'替换为'@ PrePersist'。 – Athlan 2013-03-23 17:25:06

+0

工程就像一个魅力:)谢谢! – biera 2013-03-23 17:31:19