gpt4 book ai didi

php - Symfony2 和 Doctrine : OneToMany relation duplicates data in the table

转载 作者:可可西里 更新时间:2023-11-01 13:12:10 25 4
gpt4 key购买 nike

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

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;
}

在我的 Controller 中,我正在做一些测试,我将坚持或不坚持某些实体。最后,我正在冲洗

$em->flush(); 

奇怪的是,在我的 Emails 表中,数据在我进行刷新后立即复制。使用

测试实体管理器时
$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" );

最佳答案

在我重现它之前我没有发现你的问题,但现在它有点明显了。您的问题来自使用 clear 方法。实际上,如果您清除您的实体管理器,它会忘记它们的存在并将它们作为新的持久化。

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

希望对你有帮助;)

祝你好运

干杯

关于php - Symfony2 和 Doctrine : OneToMany relation duplicates data in the table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20705172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com