我有以下实体:
/**
* @ORMEntity
*/
class Product
{
/**
* @ORMId
* @ORMColumn(type="integer")
* @ORMGeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORMManyToOne(targetEntity="Category", inversedBy="products")
* @ORMJoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
}
和:
/**
* @ORMEntity
*/
class Category
{
/**
* @ORMId
* @ORMColumn(type="integer")
* @ORMGeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORMOneToMany(targetEntity="Product", mappedBy="category", fetch="EXTRA_LAZY")
*/
protected $products;
/**
* @ORMColumn(type="integer")
*/
protected $productCount = 0;
public function updateProductCount()
{
$this->productCount = $this->products->count();
}
}
我希望无论何时更新/添加/删除类别的相关产品,都能更新类别的productCount
字段。我已经创建了方法Category::updateProductCount()
来做到这一点,但不确定最佳方法。
有什么帮助吗?
这不是PHP的职责,您应该使用sql触发器。我认为你的数据库中不应该有count属性。例如,你可以做:
- 从产品中选择count(*),其中category=
- 创建SQL视图
我想这就是您想要的:Doctrine2生命周期事件尝试$this->productCount = count($this->products);
而不是$this->productCount = $this->products->count();
我不知道你为什么要把它存储在数据库中。我只想用一个吸气剂:
public function getProductCount(){ return count($this->products); }