原则插入postPersist事件 [英] Doctrine inserting in postPersist event
问题描述
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屋!