Nic*_*ick 0 events doctrine-orm
我大量使用实体监听器进行日志记录,通常工作得很好并且将所有代码保留在控制器/服务之外.
我无法实现的一件事是记录添加到ManyToMany关系的项目.在这种情况下,我想记录从产品中添加/删除大小的时间
/**
* @ORM\Entity
* @ORM\EntityListeners({"EventListener\ProductListener"})
* @ORM\Table(name="products")
*/
class Product
{
// ...
/**
* @var ArrayCollection
*
* @ORM\ManyToMany(targetEntity="Size")
* @ORM\JoinTable(name="productSizes",
* joinColumns={@ORM\JoinColumn(name="productId", referencedColumnName="productId")},
* inverseJoinColumns={@ORM\JoinColumn(name="sizeId", referencedColumnName="sizeId")}
* )
*/
protected $sizes;
/**
* @param Size $size
* @return Product
*/
public function addSize(Size $size)
{
$this->sizes[] = $size;
return $this;
}
/**
* @param Size $size
*/
public function removeSize(Size $size)
{
$this->sizes->removeElement($size);
}
/**
* @return ArrayCollection
*/
public function getSizes()
{
return $this->sizes;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
然后在实体监听器内部
class ProductListener
{
// ...
/**
* @ORM\PostPersist
*/
public function postPersistHandler(Product $product, LifecycleEventArgs $args)
{
$this->getLogger()->info("Created product {$product->getSku()}", [
'productId' => $product->getId()
]);
}
/**
* @ORM\PostUpdate
*/
public function postUpdateHandler(Product $product, LifecycleEventArgs $args)
{
$context = $args->getEntityManager()->getUnitOfWork()->getEntityChangeSet($product);
$context['productId'] = $product->getId();
$this->getLogger()->info("Updated product", $context);
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
那么如何才能从工作单元中添加/删除颜色?我假设这在某处可用,但我找不到它.
小智 8
在ProductListener中
$product->getSizes() returns instance of Doctrine\ORMPersistentCollection. Then you can call 2 methods:
- getDeleteDiff - returns removed items
- getInsertDiff - returns added items
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
974 次 |
最近记录: |