相关疑难解决方法(0)

在Doctrine Entity Listener的preUpdate中保留其他实体

为了清楚我在这里继续讨论开始在这里.

Doctrine Entity Listener中,在preUpdate方法中(我可以访问实体任何字段的旧值和新值)我试图保持与焦点实体无关的实体.

基本上我有实体A,当我在我想要写的一个字段中更改一个值时,在project_notification表中,字段oldValue,newValue加上其他字段.

如果我没有在preUpdate方法中刷新,则新通知实体不会存储在DB中.如果我冲洗它,我进入一个无限循环.

这是preUpdate方法:

public function preUpdate(ProjectTolerances $tolerances, PreUpdateEventArgs $event)
{
    if ($event->hasChangedField('riskToleranceFlag')) {
    $project = $tolerances->getProject();                
    $em = $event->getEntityManager();
    $notification = new ProjectNotification();
    $notification->setValueFrom($event->getOldValue('riskToleranceFlag'));
    $notification->setValueTo($event->getNewValue('riskToleranceFlag'));
    $notification->setEntity('Entity'); //TODO substitute with the real one
    $notification->setField('riskToleranceFlag');
    $notification->setProject($project);
    $em->persist($notification);


    // $em->flush(); // gives infinite loop
    }
}
Run Code Online (Sandbox Code Playgroud)

谷歌搜索了一下我发现你不能在监听器内调用flush,这里建议将这些东西存放在一个数组中,以便稍后在onFlush中进行刷新.尽管如此它不起作用(并且它可能不起作用,因为在调用preUpdate之后,侦听器类的实例会被破坏,因此当您稍后调用onFlush时,无论您在类级别保存为protected属性都会丢失或者我错过了什么?).

以下是监听器的更新版本:

class ProjectTolerancesListener
{
    protected $toBePersisted = [];

    public function preUpdate(ProjectTolerances $tolerances, PreUpdateEventArgs $event)
    {
        $uow = $event->getEntityManager()->getUnitOfWork();
//        $hasChanged = false;

        if ($event->hasChangedField('riskToleranceFlag')) {
        $project …
Run Code Online (Sandbox Code Playgroud)

symfony doctrine-orm

18
推荐指数
3
解决办法
1万
查看次数

如何在Symfony 2.4中使用Doctrine Entity Listener?

我想在Symfony 2.4中使用Doctrine Entity Listener.

我创建了一个类:

<?php

namespace MyBundle\Listener\Entity;

use Doctrine\ORM\Event\LifecycleEventArgs;
use MyBundle\Entity\User;

class UserListener
{
    public function postPersist(User $user, LifecycleEventArgs $event)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我添加了映射信息:

<?xml version="1.0" encoding="UTF-8" ?>
<doctrine-mapping>
    <entity name="MyBundle\Entity\User">

        ...

        <entity-listeners>
            <entity-listener class="MyBundle\Listener\Entity\UserListener" />
        </entity-listeners>

    </entity>
</doctrine-mapping>
Run Code Online (Sandbox Code Playgroud)

它工作正常.但是如何将一些服务传递给这个类呢?我希望它与Symfony的服务容器集成并提供服务.

doctrine symfony

4
推荐指数
1
解决办法
7089
查看次数

标签 统计

symfony ×2

doctrine ×1

doctrine-orm ×1