如何使用 Doctrine2 更新关联实体?
Frame 与 Photo 具有单向的一对一关联。
- 我想现在每个框架都与一张照片相关联。
- 我还猜测照片不存储有关框架的信息。
- 我想知道哪个照片在框架中(在框架中放置照片)
- 我不想知道照片位于哪个框架中
- 我假设我可以在更多<中放置照片/strong> 超过一帧!
到目前为止,一切都按预期进行:
$photo = new Photo();
$another_photo = new Photo();
$frame = new Frame();
$frame->setPhoto($photo);
$em->persist($frame);
$em->flush();
创建了框架和两张照片,并且框架与数据库中的 $photo 连接。我可以使用 getPhoto() 查询 $frame 并获取 $photo。
但我现在想更新框架的照片,但它不起作用:
$frame = $em->getRepository('Frame')->findOneById(id_of_frame);
$frame->setPhoto($another_photo);
$em->persist($frame);
$em->flush();
并出现原则错误: 通过关系“Frame#Photo”找到了一个新实体,该实体未配置为级联实体的持久操作。显式保留新实体或在关系上配置级联保留操作。
我可以在 Frame OneToOne 关系内设置cascade="persist",并且错误不再发生,但我收到有关未保留颜色的新错误我在照片中使用了它,但我确实没有设置和想要:(
为什么我会收到错误?为什么我需要坚持级联框架和照片?
谢谢!
Frame has a unidirectional oneToOne association to Photo.
- I guess every Frame is associated with a Photo now.
- I also guess that a Photo stores no information about the Frame.
- I want to know which Photo is in a Frame (Have a Photo in a Frame)
- I don't want to know about in which Frame a Photo is located
- I assume that I'm able to have a Photo in more than one Frames!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您如何创建 $another_photo?
由于它已经在数据库中,因此您需要执行以下操作:
$another_photo = $entityManager->getReference('照片',$another_photo_id);
顺便说一下,整个级联的事情可能会变得非常混乱。我想您会发现在创建新照片时保留它们会更安全。
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.