2017-05-20 41 views
0

我有兩個實體產品和類別與類型多對一的關聯,應該我想創建一個新的產品,我已經知道它的類別(指我知道ID類)主義Symfony2的持續關聯實體與現有

CLASS產品

/** 
* @ORM\Entity 
* @ORM\Table(name="product") 
*/ 
class Product 
{ 
    /** 
    * @ORM\Column(type="integer") 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    private $id; 

    /** 
    * @ORM\Column(type="string", length=100) 
    */ 
    private $name; 

    /** 
    * @ORM\ManyToOne(targetEntity="Category") 
    * @ORM\JoinColumn(name="category_id", referencedColumnName="id") 
    */ 
    private $category; 
} 

Class類

/** 
* @ORM\Entity 
* @ORM\Table(name="category") 
*/ 
class Category 
{ 
    /** 
    * @ORM\Column(type="integer") 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    private $id; 
} 

SCRNARIO:科瑞新產品,並認爲我知道ID的類別,所以我們不需要給我們E類實體的查找方法得到它(使事情更快)

$em = $this->get('doctrine')->getManager(); 
$category = new Category(); 
$category->setId(12); 
$product = new Product(); 
$product->setName('product 1'); 
$product->setCategory($category); 
$em->persist($product); 
$em->flush(); 

上面的代碼沒有工作,那麼產生一個異常:

一個新的實體是通過關係 「發現AOBundle \實體\產品#分類」中沒有配置級聯 持續操作的實體: AOBundle \實體\目錄@ 0000000049a05dc500000000723a1be6。要解決 此問題:顯式調用此未知實體上的EntityManager#persist()或配置級聯在 映射中保留此關聯,例如@ManyToOne(..,cascade = {「persist」})。如果你不能 找出哪些實體引起該問題落實 「AOBundle \實體\目錄#__的toString()」,以獲得一個線索。

但是當我使用find方法來獲取它的工作類別實例,但我不喜歡這個解決方案我想讓應用程序更快有沒有任何解決方案。 感謝

+0

乾淨的方法是獲取實體(例如使用' - > find(12)' - 我不知道爲什麼你會這麼做以避免這種情況...你可以嘗試*'$類= $ EM->合併($類);''你$分類 - > SETID(12)之後;'呼叫 – ccKep

+0

查找學說引用避免了需要實際加載的實體$類= $ EM - > getReference(12); – Cerad

回答

0

您可以使用EntityManager的getReference方法。

您的代碼應該是這樣的。

$em = $this->get('doctrine')->getEntityManager(); 
$category = $em->getReference('AppBundle:Category', 12); 

$product = new Product(); 
$product->setName('product 1'); 
$product->setCategory($category); 

$em->persist($product); 
$em->flush(); 
+0

這就是我需要的類別的對象,而不去數據庫。謝謝 –

0

錯誤意味着,如果你堅持下去的產品,你需要使用級聯,因爲您尚未創建類別。

所以,你可以做這樣的事情:

$em = $this->get('doctrine')->getManager(); 
$category = new Category(); 
$category->setId(12); 
$em->persist($category); 

$product = new Product(); 
$product->setName('product 1'); 
$product->setCategory($category); 
$em->persist($product); 
$em->flush(); 

我不知道爲什麼你設置的類別ID,但我建議你刪除它

+0

ID爲12類是已經在數據庫中,爲什麼我會創造一個又一個,這是違反主要約束 –

0

也許你沒有選擇已有的類別。

$em = $this->get('doctrine')->getManager(); 
$category = $em->getRepository('AppBundle:Category')->find(12); 

$product = new Product(); 
$product->setName('product 1'); 
$product->setCategory($category); 

$em->persist($product); 
$em->flush(); 
+1

,你可以在我的問題,我用find方法看,我的問題是如何創建類別12的新產品,而無需調用方法查找。只需創建一個ID爲12的類別並堅持產品 –

+0

我不知道這種技術,謝謝。 –

相關問題