原则插入postPersist事件 [英] Doctrine inserting in postPersist event

查看:176
本文介绍了原则插入postPersist事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在实体持久化和更新时添加新的Feed项。我写这个事件监听器(postUpdate是一样的):

  public function postPersist(LifecycleEventArgs $ args)
{
$ entity = $ args-> getEntity();
$ em = $ args-> getEntityManager();

if($ entity instanceof FeedItemInterface){
$ feed = new FeedEntity();
$ feed-> setTitle($ entity-> getFeedTitle());
$ feed-> setEntity($ entity-> getFeedEntityId());
$ feed-> setType($ entity-> getFeedType());
if($ entity-> isFeedTranslatable()){
$ feed-> getEnTranslation() - > setTitle($ entity-> getFeedTitle('en'));
}
$ em-> persist($ feed);
$ em-> flush();
}
}

但是我有


完整性约束违规:1062密钥
'PRIMARY'的重复条目'30 -2'

在日志中有两个插入:


INSERT INTO interview_scientificdirection(interview_id,
scientificdirection_id) VALUES(?,?)([30,2])INSERT INTO
interview_scientificdirection(interview_id,scientificdirection_id)
VALUES(?,?)([30,2])


科学方向是实体的多对多关系表,我们想要坚持。
在前端应用程序中,一切都可以正常工作,但在Sonata Admin中我遇到了这个问题:(

解决方案

自从Doctrine 2.2可以将侦听器附加到postFlush事件:

  function postFlush($ args){
$ em = $ args-> getEntityManager();
foreach($ em-> getUnitOfWork() - > getScheduledEntityInsertions()as $ entity){
if($ entity instanceof FeedItemInterface){
$ feed = new FeedEntity;
...
$ em-> persist($ feed);
}
}
$ em-> flush();
}


I want add new Feed item on entity persist and update. I write this event listener (postUpdate is same):

public function postPersist(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();
    $em = $args->getEntityManager();

    if ($entity instanceof FeedItemInterface) {
        $feed = new FeedEntity();
        $feed->setTitle($entity->getFeedTitle());
        $feed->setEntity($entity->getFeedEntityId());
        $feed->setType($entity->getFeedType());
        if($entity->isFeedTranslatable()) {
            $feed->getEnTranslation()->setTitle($entity->getFeedTitle('en'));
        }
        $em->persist($feed);
        $em->flush();
    }
}

But I got

Integrity constraint violation: 1062 Duplicate entry '30-2' for key 'PRIMARY'

and in log a have two insertations:

INSERT INTO interview_scientificdirection (interview_id, scientificdirection_id) VALUES (?, ?) ([30,2]) INSERT INTO interview_scientificdirection (interview_id, scientificdirection_id) VALUES (?, ?) ([30,2])

scientificdirection is Many to Many relationship table for entity what we want to persist. In frontend application everything work fine, but in Sonata Admin I got this problem :(

解决方案

Since Doctrine 2.2 you can attach listeners to a postFlush event:

function postFlush($args) {
    $em = $args->getEntityManager();
    foreach ($em->getUnitOfWork()->getScheduledEntityInsertions() as $entity) {
        if ($entity instanceof FeedItemInterface) {
            $feed = new FeedEntity;
            ...
            $em->persist($feed);
        }
    }
    $em->flush();
}

这篇关于原则插入postPersist事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆