原则 2:批量处理引用其他实体的实体插入时的奇怪行为
我正在尝试这里描述的批处理方法: http://docs.doctrine-project .org/projects/doctrine-orm/en/latest/reference/batch-processing.html
我的代码看起来像这样,
$limit = 10000;
$batchSize = 20;
$role = $this->em->getRepository('userRole')->find(1);
for($i = 0; $i <= $limit; $i++)
{
$user = new \Entity\User;
$user->setName('name'.$i);
$user->setEmail('email'.$i.'@email.blah');
$user->setPassword('pwd'.$i);
$user->setRole($role);
$this->em->persist($user);
if (($i % $batchSize) == 0) {
$this->em->flush();
$this->em->clear();
}
}
问题是,在第一次调用 em->flush() 之后 $role 被分离,每 20 个用户就有一个具有新 id 的新角色 创建了,这不是我想要的,
对于这种情况有什么解决方法吗?我唯一能做的就是每次在循环中获取用户角色实体,
谢谢
I am trying out the batch processing method described here:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/batch-processing.html
my code looks like this
$limit = 10000;
$batchSize = 20;
$role = $this->em->getRepository('userRole')->find(1);
for($i = 0; $i <= $limit; $i++)
{
$user = new \Entity\User;
$user->setName('name'.$i);
$user->setEmail('email'.$i.'@email.blah');
$user->setPassword('pwd'.$i);
$user->setRole($role);
$this->em->persist($user);
if (($i % $batchSize) == 0) {
$this->em->flush();
$this->em->clear();
}
}
the problem is, that after the first call to em->flush() also the
$role gets detached and for every 20 users a new role with a new id is
created, which is not what i want
is there any workaround available for this situation? only one i could make work is to fetch the user role entity every time in the loop
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
clear()
分离由实体管理器管理的所有实体,因此$role
也被分离,并且尝试持久化分离的实体会创建一个新实体。您应该在清除后再次获取角色:
或者只是创建一个引用:
clear()
detaches all entities managed by the entity manager, so$role
is detached too, and trying to persist a detached entity creates a new entity.You should fetch the role again after clear:
Or just create a reference instead:
作为 arnaud576875 答案的替代方案,您可以将 $user 从实体管理器中分离,以便立即对其进行 GC。像这样:
编辑:
正如 Geoff 所指出的,这将仅分离最新创建的用户对象。所以不推荐这种方法。
As an alternative to arnaud576875's answer you could detach the $user from the entity manager so that it can be GC'd immediately. Like so:
Edit:
As pointed out by Geoff this will only detach the latest created user-object. So this method is not recommended.