php - 如何检查 Doctrine 2 中的实体是否更改?

标签 php doctrine doctrine-orm

我需要检查持久化实体是否已更改并需要在数据库中更新。 我所做的(但没有工作)如下:

$product = $entityManager->getRepository('Product')->find(3);
$product->setName('A different name');

var_export($entityManager->getUnitOfWork()->isScheduledForUpdate($product));

那个代码总是打印false,我也试过在检查工作单元之前flush,但是没有用。

有人有什么建议吗?

最佳答案

我首先会检查你的 setName 函数是否确实在做某事($this-> name = $name...)如果它已经在工作,那么你可以定义一个事件调用刷新时触发的 services.yml 上的监听器。

entity.listener:
  class: YourName\YourBundle\EventListener\EntityListener
  calls:
    - [setContainer,  ["@service_container"]]
  tags:
    - { name: doctrine.event_listener, event: onFlush }

然后定义EntityListener

namespace YourName\YourBundle\EventListener;

use Doctrine\ORM\Event;
use Symfony\Component\DependencyInjection\ContainerAware;

class EntityListener extends ContainerAware
{   

    /**
     * Gets all the entities to flush
     *
     * @param Event\OnFlushEventArgs $eventArgs Event args
     */
    public function onFlush(Event\OnFlushEventArgs $eventArgs)
    {   
        $em = $eventArgs->getEntityManager();
        $uow = $em->getUnitOfWork();

        //Insertions
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
            # your code here for the inserted entities
        }

        //Updates
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
            # your code here for the updated entities
        }

        //Deletions
        foreach ($uow->getScheduledEntityDeletions() as $entity) {
            # your code here for the deleted entities
        }
    }
}

如果您需要知道哪些实体正在被更改,但它们被保存到数据库后对它们做一些事情,只需将更改的实体存储在一个私有(private)数组中,然后定义一个从数组中获取实体的 onFlush 事件。

顺便说一句,要触发此类事件,您需要在实体上添加 @ORM\HasLifecycleCallbacks。

关于php - 如何检查 Doctrine 2 中的实体是否更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10800178/

相关文章:

php - 无法使用此命令安装 oro 平台 sudo php app/console oro :install --env ="dev"

php - Doctrine 没有加载类 MappingException

php - Symfony 2 Doctrine MS SQL 错误

symfony - Doctrine "A new entity was found through the relationship"错误

mysql - 使用 Doctrine QueryBuilder 的 Select 语句的 INNER JOIN 结果

php - 将文件的上次修改日期/时间与当前日期/时间进行比较?

php - 使用 PHP + sqlsrv 更新 MSSQL 表

javascript - 大型 sql 表 - 选择所有但使用 javascript/PHP 逐步显示

php - 从 PHP 应用程序通过网络打印

mysql - 创建查询,当条件为真时添加两个值或仅获取一个值