Symfony 如何使用Doctrine2在persist/delete/update上更新相关实体的列

Symfony 如何使用Doctrine2在persist/delete/update上更新相关实体的列,symfony,doctrine-orm,Symfony,Doctrine Orm,我拥有以下实体: /** * @ORM\Entity */ class Product { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\ManyToOne(targetEntity="Category", inversedBy="produ

我拥有以下实体:

/**
 * @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;
}
以及:

我希望在更新/添加/删除类别的相关产品时更新类别的productCount字段。我创建了方法Category::updateProductCount来实现这一点,但我不确定最佳方法


有什么帮助吗?

这不是PHP的职责,您应该使用sql。我认为数据库中不应该有count属性。例如,您可以执行以下操作:

从类别=。。。 创建SQL视图
我想这就是你想要的: 而不是$this->productCount=$this->products->count;尝试$this->productCount=count$this->products

我不知道你为什么要把它存储在数据库里。我只需要使用一个getter:

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

在数据库中存储的原因基本上是为了性能——列出100个类别及其产品数量将创建100个查询。我知道我可以使用虚拟计数列,但这会使水合作用成为一个问题。谢谢,我使用了sql触发器来实现这一点。我明白我真的不应该有一个计数列。这个解决方案很好地使用了我的ORM,并且保持了它的简单性。
public function getProductCount(){ return count($this->products); }