0

次のエンティティがあります。

/**
 * @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()が、最善の方法がわかりません。

何か助けはありますか?

4

2 に答える 2