Doctrine 2多级OneToOne Cascade

Tae*_*ram 6 php mapping orm doctrine doctrine-orm

我有三个Doctrine实体:Device,它与Device\Status具有OneToOne关系,后者与Device\Status\Battery具有OneToOne关系.

我在相关实体之间设置了{cascade ="persist"},并且从我读过的内容中,应该是Doctrine自动保存每个实体所需的全部内容,而无需在代码中自行执行任何操作.

这是我遇到的问题:

$device = new \Entities\Device();
$device->setId(100);

$status = $device->getStatus();
$status->setIpAddress('192.168.0.1');

$battery = $status->getBattery();
$battery->setInternalLevel(60);

$em->persist($device);
$em->flush();
Run Code Online (Sandbox Code Playgroud)

执行此代码后,我收到以下错误:

Entity of type Device\Status\Battery has identity through a foreign entity 
Device\Status, however this entity has no identity itself. You have to call 
EntityManager#persist() on the related entity and make sure that an identifier 
was generated before trying to persist 'Device\Status\Battery'. In case of 
Post Insert ID Generation (such as MySQL Auto-Increment or PostgreSQL SERIAL) 
this means you have to call EntityManager#flush() between both persist 
operations.
Run Code Online (Sandbox Code Playgroud)

我的问题是:设置我的实体以确保它们以正确的顺序持续存在的正确方法是什么?

可以在此处找到实体的代码:https://gist.github.com/1753524

所有测试都是使用Doctrine 2.2沙箱进行的.

jer*_*ere 6

我认为@CappY是对的.

问题出在Status实体中.当您执行getBattery()并创建新的Battery实例时,它与您调用的Status实例相关getBattery().

由于该实例尚未存储在数据库中,因此尚未生成它的id(因为它被注释为@GeneratedValue).你对瀑布持续存在几乎是正确的.除了它在内存中执行.

所以,你需要做之前坚持和冲洗状态的实体getBattery(),如果要使用该实体作为电池ID.或者你可以简单地为电池添加一个id字段:)