Reputation: 879
I just fetch an entity (row) from database:
$one = $em->getRepository()->find(1);
and trying to insert another entity which has foreign key with $one
:
for($i=0; $i<=100; $i++) {
$two = new TwoEntity();
$two->setOne($one); // as you can see $one is just a foreign key. Referenced.
$two->setSomething(true);
$em->persist($two);
...
// when each 20th cycle flush them. and clear.
$em->flush();
$em->clear();
}
Note: I use Doctrine2' s batch insert way. I just minimized the code for shorter explanation what im trying to do.
Instead of referencing $one
, Doctrine trying to re-insert $one
. It gives persist exception and if i persist $one
, it just trying to insert $one
over again and again. Error: A new entity was found through the relationship...
How can I just reference $one
and only insert $two
in batch?
Update: I tried also $one->addTwo($two)
method on $one
but this time errors gone but foreign key fields are empty.
I did Side Owning
and Side Inverse
to cascade all. This way if i merge $em->merge($one)
it just works. But, I don't know if this is the correct way.
Upvotes: 0
Views: 97
Reputation: 782
You do $em->clear();
so $one
is just not referenced anymore in Doctrine.
Docblock of clear method say :
Clears the ObjectManager. All objects that are currently managed by this ObjectManager become detached.
Just remove $em->clear();
or use something like this $em->clear('TwoEntity');
Upvotes: 1
Reputation: 7764
This is incorrect:
$two->setOne($one); // as you can see $one is just a foreign key. Referenced.
What you need to do is something like this:
$two->setOne( $one->getId() );
Or something like that. In other words get the reference id. Right now, you are setting an object, not an identifier. Unless you truly want to add the object to the new Entity $two, which you would do differently. Let us know if that's the case.
Upvotes: 0