2013-08-06 65 views
0
刪除/更新

我有以下實體:如何更新相關實體對堅持列/與Doctrine2

/** 
* @ORM\Entity 
*/ 
class Product 
{ 
    /** 
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    protected $id; 

    /** 
    * @ORM\ManyToOne(targetEntity="Category", inversedBy="products") 
    * @ORM\JoinColumn(name="category_id", referencedColumnName="id") 
    */ 
    protected $category; 
} 

和:

/** 
* @ORM\Entity 
*/ 
class Category 
{ 
    /** 
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    protected $id; 

    /** 
    * @ORM\OneToMany(targetEntity="Product", mappedBy="category", fetch="EXTRA_LAZY") 
    */ 
    protected $products; 

    /** 
    * @ORM\Column(type="integer") 
    */ 
    protected $productCount = 0; 

    public function updateProductCount() 
    { 
     $this->productCount = $this->products->count(); 
    } 
} 

我想類別的productCount領域是每當其相關產品更新/添加/刪除時更新。我已經創建了方法Category::updateProductCount()來做到這一點,但我不確定最佳方法。

任何幫助?

回答

1

這不是PHP的角色,你應該使用sql trigger。我認爲你不應該在你的數據庫中擁有數量屬性。例如,你可以這樣做:

  • SELECT COUNT(*)從產品類別爲...
  • 創建一個SQL視圖
+0

謝謝,我用sql觸發器來實現這一點。我知道我真的不應該有一個計數列這個解決方案與我的ORM很好,並保持簡單。 –

1

我認爲這是你在尋找什麼:Doctrine2 LifeCycle Events 相反$this->productCount = $this->products->count();嘗試$this->productCount = count($this->products);

我不知道爲什麼你必須將它存儲在數據庫中。我只想用一個getter:

public function getProductCount(){ return count($this->products); } 
+0

存儲在數據庫中的原因基本上是爲了性能 - 列出100個產品數量的類別將創建100個COUNT個查詢。我知道我可以使用「虛擬」數列,但這會使水合作用成爲問題。 –