創建事件偵聽器Post
實體preUpdate
,觸發很好,但是當我嘗試更新相關實體Category
,它拋出一個錯誤:如何使用EventListener更新相關實體?
Field "category" is not a valid field of the entity "BW\BlogBundle\Entity\Post" in PreUpdateEventArgs.
我的事件監聽器代碼:
public function preUpdate(PreUpdateEventArgs $args) {
$entity = $args->getEntity();
$em = $args->getEntityManager();
if ($entity instanceof Post) {
$args->setNewValue('slug', $this->toSlug($entity->getHeading())); // work fine
$args->setNewValue('category', NULL); // throw an error
// other code...
我的帖子實體代碼:
/**
* Post
*
* @ORM\Table(name="posts")
* @ORM\Entity(repositoryClass="BW\BlogBundle\Entity\PostRepository")
*/
class Post
{
/**
* @var string
*
* @ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* @var integer
*
* @ORM\ManyToOne(targetEntity="\BW\BlogBundle\Entity\Category")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
// other code
如何更新此Category
實體在這個EvenetListener中與Post
實體一樣在我的例子中?
This answer work,but only for Post
changes。但我也需要改變Category
實體的一些值,比如:
$entity->getCategory()->setSlug('some-category-slug'); // changes not apply, nothing happens with Category entity.
難道你不能簡單地做'$ entity-> setCategory(null)'? –
@AlbertoFernández是的,我可以,但它什麼都不做。順便說一下,'$ entity-> setSlug('new-slug')'也無能爲力。對於它的工作,我需要使用'setNewValue',但與相關的實體它不會工作。 –