Stefan
Stefan

Reputation: 365

How to update an associated entity with Doctrine2?

Frame has a unidirectional oneToOne association to Photo.

By now everything worked as expected:

$photo = new Photo();
$another_photo = new Photo();
$frame = new Frame();
$frame->setPhoto($photo);

$em->persist($frame);
$em->flush();

Frame and two Photos are created and the Frame is connected with $photo in the DB. I can query $frame and get $photo with getPhoto().

But I want to update the Photo of a Frame now and it does not work:

$frame = $em->getRepository('Frame')->findOneById(id_of_frame);
$frame->setPhoto($another_photo);
$em->persist($frame);
$em->flush();

And get a Doctrine Error: A new entity was found through the relationship 'Frame#Photo' that was not configured to cascade persist operations for entity. Explicitly persist the new entity or configure cascading persist operations on the relationship.

I can set a cascade="persist" inside the Frame OneToOne relation and the error does not occur any more but I get a new error about not persisted color which I use in the Photo which I truly do not set and want :(

Why do I get the error at all? Why do I need to persist cascade the Frame and the Photo?

Thanks!

Upvotes: 0

Views: 1178

Answers (1)

Cerad
Cerad

Reputation: 48865

How are you creating $anothor_photo? Since it is already in the database, you will need to do something like: $another_photo = $entityManager->getReference('Photo',$another_photo_id);

By the way, the whole cascade thing can become quite confusing. I think you will find that it safer to just persist new photos when you create them.

Upvotes: 1

Related Questions