Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

php - Doctrine 2: weird behavior while batch processing inserts of entities that reference other entities

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 EntityUser;
        $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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

$this->em->clear();
$role = $this->em->getRepository('userRole')->find(1);

Or just create a reference instead:

$this->em->clear();
$role = $this->em->getReference('userRole', 1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...