18

我的实体中有这个方法:

/**
     * @ORM\PreUpdate()
     * @ORM\PrePersist()
     */
    public function preStore() {
        if ($this->getPictureFile()) {
            $newFilename = sha1(mt_rand());
            $newFilename = $newFilename . '.' . ($this->getPictureFile()->guessExtension());
            $this->setPictureFilename($newFilename);
        }
    }

当持久化对象时,一切正常,但在更新时根本不会触发该方法,我以这种方式对其进行了测试:

/**
     * @ORM\PreUpdate()
     * @ORM\PrePersist()
     */
    public function preStore() { var_dump('asdasdasdadsdasdas');
        if ($this->getPictureFile()) {
            $newFilename = sha1(mt_rand());
            $newFilename = $newFilename . '.' . ($this->getPictureFile()->guessExtension());
            $this->setPictureFilename($newFilename);
        }
    }

并且坚持 var_dump 有效,但是当我更新对象时 - 它没有。为什么?

4

4 回答 4

50

A update does only occur if a entity field (watched from doctrine) gets changed and so on the preupdate method is only called after a change.

Caution: i guess your picture file is not a doctrine column and so on not watched by doctrine. So your entity does not change for doctrine.

From How to handle File Uploads with Doctrine cookbook article

The PreUpdate and PostUpdate callbacks are only triggered if there is a change in one of the entity's field that are persisted. This means that, by default, if you modify only the $file property, these events will not be triggered, as the property itself is not directly persisted via Doctrine. One solution would be to use an updated field that's persisted to Doctrine, and to modify it manually when changing the file.

EDIT: Or you use the Uploadable behavior of the doctrine extensions

于 2013-06-29T16:32:42.073 回答
10

您必须明确告诉学说您的实体具有生命周期回调:

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class YourClass

此外,()如果您不提供任何选项,则不需要注释中的尾随。

/**
 * @ORM\PrePersist
 * @ORM\PreUpdate
 */
public function preStore()

考虑使用侦听器/订阅者而不是生命周期回调,以便更轻松地重用并保持实体更清洁。

更多信息可以在食谱章节How to Register Event Listeners and Subscribers中找到。

于 2013-06-29T15:08:41.927 回答
3

我遇到了同样的问题,这是我的解决方案:

添加一个映射字段并在您的内部updatedAt调用this 将触发实体setUpdatedAt(new \DateTime())setterUploadedFilepreUpdate-Event

于 2015-11-20T13:56:44.870 回答
0

这可能失败的另一个原因是如果您只有一个星号

失败: /* @ORM\PrePersist */

成功: /** @ORM\PrePersist */

荒谬,但它在那里..

于 2015-08-12T20:45:21.953 回答