使用Doctrine 2.x的Doctine 2.0緩存和默認
一些,如果在我的領域實體映射到表中只有一行 - 這是爲了支持額外的複雜性的道路(計劃 - 所以這不適合YAGNI)。
例如,考慮簡單的實體
Category\Type:
type: entity
table: category_type
id:
id:
type: integer
generator:
strategy: AUTO
fields:
name:
type: string
在我此刻的應用程序,我只有一個類別類型(NAME =「常規」),但每次我創建一個新的類別(實體未顯示 - 使用你的想象力;它與Category \ Type具有N:1的關係)我需要將類型與類別關聯。這意味着必須從數據庫中檢索單行,然後設置關聯。
$category = new Category();
$type = $em->getRepository('Category\Type')->findByName('regular');
$category->setType($type);
$em->persist($category);
$em->flush();
我想知道如何避免這樣做。
如果我只是用一個新的類型是這樣的...
$category = new Category();
$type = new Category\Type();
$type->setName('regular');
$category->setType($type);
$category->setId(1); // <-- This gets incremented anyway after the persist is called
$em->persist($category);
$em->flush();
然後主義試圖插入類型爲一個新的實體(實際上它失敗,因爲該名稱列在數據庫中的唯一約束)。
我試圖做以上,然後使用合併
http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-objects.html#merging-entities
但同樣的事情發生。
我在這裏錯過了什麼?我如何才能獲得學說來將新對象視爲已經在數據庫中,或者如何在代碼級別上緩存託管實體。
在代碼中有效'緩存'這是否不合適 - 我應該使用其他緩存機制之一嗎?
我認爲你不能。當你創建一個新的對象時,你需要建立一個關聯到一個現有的對象'Category \ Type',它將會......新的*,它將在數據庫中創建一個新的行,並且你的關聯將指向你必須獲取現有的。它是如何設計原則的,你使用對象的實例,而不是數據庫中的行。 – venimus