Symfony2和Doctrine:OneToMany关系复制表中的数据

 手机用户2502909811 发布于 2023-02-08 20:44

我有两个表:文章和电子邮件.电子邮件表将包含与特定文章相关的电子邮件,例如:

id    |  article_id |     email
1     |      1      |  test@etest.com
2     |      1      |  test2@test.com
3     |      2      |  test@etest.com
4     |      2      |  test3@test.com

等等....

article_id与articles表中的id之间存在关系.

在我的实体中,我有这个代码:

class Articles
{ 
    ....
     /**
      * @ORM\OneToMany(targetEntity="\Acme\DemoBundle\Entity\Emails", mappedBy="articles")
      */
      private $emails_rel; 

    ...
}

class Emails
{ 
    /**
     * @ORM\ManyToOne(targetEntity="\Acme\DemoBundle\Entity\Articles", inversedBy="emails_rel", cascade={"all"})
     * @ORM\JoinColumn(name="article_id", referencedColumnName="id")
     **/
    private $articles; 
}

在我的控制器中,我正在做一些测试,我将坚持或不坚持某些实体.最后,我正在做同花

$em->flush(); 

而奇怪的行为是,在我的电子邮件表中,一旦我进行刷新,数据就会被复制.使用时测试实体管理器

$em->getUnitOfWork()->getScheduledEntityInsertions()

我得到一个空数组.

知道为什么吗?非常感谢你.

编辑:

这是测试:

$articl = new Articles();
$articl = $em->createQuery("SELECT p FROM Acme\DemoBundle\Entity\Articles p WHERE p.bMailToMatch = 1")->getResult();
$nb = count($articl);

// BECAUSE I WILL WORK WITH A LOTS OF ENTRIES - PREVENT MEMORY OVERFLOW
$em->clear();    

if(isset( $articl )) {
    foreach($articl as $i => $art) {
        $array_emails = null;

        $art_emails = $art->getEmailsRel();
        foreach ($art_emails as $e) {
            $array_emails[] = $e->getEmail();
        }

        $art_id = $art->getId ();
        echo "\n\n---------- $i ----------\n " . $art->getDoi ();

        // TAKES ARTICLE WITH ZERO EMAIL
        if (!isset($array_emails) ) {
            $updated_article = $em->getRepository('AcmeDemoBundle:Articles')->findOneBy(array( 'id' => ($art_id)    )) ; 
            // Because of the clearing of the entity manager
            echo"\n\n$art_id Article DOI \n".$updated_article->getDoi();
            echo "\n==>Put the BMailToMatch's flag to 0";
            $updated_article->setBMailToMatch(0);
            $em->persist($updated_article);
        }
        else {
            echo " ==> ok\n";
        }

        if (($i % 3) == 0) {
            $em->flush();
            $em->clear();
        }
    }

    $em->flush();
    $em->clear();
}

return new Response ( "\n\nFinished!!\n" );             

lenybernard.. 9

在我复制它之前我没有发现你的问题,但现在它显而易见了.您的问题来自于使用clear方法.实际上,如果你清除你的实体经理,它会忘记它们的存在,并将它们作为新的存在.

如果您遇到性能问题,可以限制处理的项目数量,并在完成之前递归执行.

我希望它能帮到你;)

祝好运

干杯

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有