Php 如何将EventListener用于更新相关实体?

Php 如何将EventListener用于更新相关实体?,php,symfony,doctrine-orm,entity,event-listener,Php,Symfony,Doctrine Orm,Entity,Event Listener,我为Post实体的preUpdate创建事件侦听器,触发了fine,但当我尝试更新相关实体类别时,它抛出了一个错误: Field "category" is not a valid field of the entity "BW\BlogBundle\Entity\Post" in PreUpdateEventArgs. 我的事件侦听器代码是: public function preUpdate(PreUpdateEventArgs $args) { $entity = $args-&

我为
Post
实体的
preUpdate
创建事件侦听器,触发了fine,但当我尝试更新相关实体
类别时,它抛出了一个错误:

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
如何在此EvenetListener中更新此
类别
实体以及示例中的
Post
实体

这项工作,但仅适用于
Post
更改。但是我还需要更改
类别
实体的一些值,例如:

$entity->getCategory()->setSlug('some-category-slug'); // changes not apply, nothing happens with Category entity.

我猜setNewValue方法只适用于已更改的字段。可能您的类别已经为空。这就是为什么它会抛出错误。下面是来自的示例代码


不,我检查了这个值,它不
NULL
。我猜方法
setNewValue
仅用于静态字段(整数、字符串等),而不是相关实体。但是我现在需要改变一个相关的实体,我很困惑。也许你可以试试这个(查看投票评论,链接到另一个主题)。谢谢,工作!但仅适用于
Post
更改。如果我试图更改
Category
entity的一些值,例如:
$entity->getCategory()->setSlug('some-Category-slug')
,什么都不会发生。你不能简单地执行
$entity->setCategory(null)
?@Albertofernandez是的,我可以,但它什么都不做。顺便说一下,
$entity->setSlug('new-slug')
也不做任何事情。对于它的工作,我需要使用
setNewValue
,但是对于相关的实体它将不起作用。
 /**
  * Set the new value of this field.
  *
  * @param string $field
  * @param mixed $value
  */
 public function setNewValue($field, $value)
 {
     $this->assertValidField($field);

     $this->entityChangeSet[$field][1] = $value;
 }

 /**
  * Assert the field exists in changeset.
  *
  * @param string $field
  */
 private function assertValidField($field)
 {
     if ( ! isset($this->entityChangeSet[$field])) {
         throw new \InvalidArgumentException(sprintf(
             'Field "%s" is not a valid field of the entity "%s" in PreUpdateEventArgs.',
             $field,
             get_class($this->getEntity())
         ));
     }