Symfony unitOfWork



我有个小问题要解决。

我有两个具有多对多关系的实体(类似于帖子和标签)我想有一个事件,被称为onFlush上post实体。这种情况是,在此事件中,我必须在进行更改之前对该帖子和基本集合的标签进行更改。第一部分我知道如何通过getschedulecollectionupdates,但如何获得将被更新的实体的基本集合?

我使用symfony 4.4和doctrine

您可以使用信条生命周期事件订阅器。

您可以在通过preUpdate方法将数据写入数据库之前执行一个操作。它还允许您访问PreUpdateEventArgs,在那里您可以获取/修改数据并做您需要的事情。

创建文件夹src/EventSubscriber,然后添加这个文件。

// src/EventSubscriber/YourEntityNameSubscriber.php
namespace AppEventSubscriber;
use DoctrineBundleDoctrineBundleEventSubscriberEventSubscriberInterface;
use DoctrineORMEventPreUpdateEventArgs;
use DoctrineORMEvents;
class YourEntityNameSubscriber implements EventSubscriberInterface
{
public function getSubscribedEvents(): array
{
return array(
Events::preUpdate,
);
}
/**
* On YourEntityName update.
*
* @param PreUpdateEventArgs $args
* @return void
*/
public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof YourEntityName) {
// Do whatever you need to do here on this specific entity..
// Example access tags $entity->getTags();
// You can use $args->hasChangedField('fieldname');
// Get data $args->getNewValue('fieldname')
// Also can change data by using $args->setNewValue('fieldname', null);
}
}
}

最新更新