我有三個Doctrine實體:Device,它與Device \ Status具有OneToOne關係,而Device \ Status與Device \ Status \ Battery具有OneToOne關係。Doctrine 2多級OneToOne級聯
我在相關實體之間設置了{cascade =「persist」},並且從我所讀到的內容來看,這應該是所有爲自動堅持每個實體所需的全部內容,而無需自己做任何事情代碼。
這裏是我有什麼用的問題:
$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();
執行此代碼後,我收到以下錯誤:
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.
我的問題是:什麼是正確的方法來設置我的實體以確保它們保持正確的順序?
爲實體的代碼可以在這裏找到:使用學說2.2沙箱已經進行https://gist.github.com/1753524
所有測試。
我有幾乎相同的問題。你必須在每次持續之間調用flush。 – CappY 2012-02-05 18:03:11
@CappY根據Doctrine文檔,因爲我爲每個實體設置了{cascade =「persist」},所以我不需要手動持久化每個實體。此代碼*應該*按原樣工作。 http://readthedocs.org/docs/doctrine-orm/en/latest/reference/working-with-associations.html#transitive-persistence-cascade-operations – Taeram 2012-02-06 04:10:21
請提供一個[簡短,自包含,正確的示例](http ://sscce.org/)。當你嘗試將值直接賦值給'protected'屬性時,你的代碼觸發訪問衝突,即'$ device-> id = 100' – Phil 2012-02-06 05:08:00