2012-06-01 131 views
2

我有2個實體:ProfileContact和配置文件。他們之間有聯繫。Doctrine2 - 堅持實體與協會沒有提取相關實體

class ProfileContact { 

    /** 
    * @var integer $profileContactId 
    * 
    * @ORM\Column(name="profile_contact_id", type="integer", nullable=false) 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="IDENTITY") 
    */ 
    private $profileContactId; 

    /** 
    * @var text $description 
    * 
    * @ORM\Column(name="description", type="text", 
    * nullable=true) 
    */ 
    private $description; 

    /** 
    * @var Profile 
    * 
    * @ORM\ManyToOne(targetEntity="Profile") 
    * @ORM\JoinColumns({ 
    * @ORM\JoinColumn(name="profile_id", 
    * nullable=false, 
    * onDelete="CASCADE", referencedColumnName="profile_id") 
    * }) 
    */ 
    private $profile; 
} 

class Profile { 

    /** 
    * @var integer $profileId 
    * 
    * @ORM\Column(name="profile_id", type="integer", nullable=false) 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="IDENTITY") 
    */ 
    private $profileId; 
} 

當然有適當的制定者和獲得者。

我應該如何創建並堅持ProfileContact實體與現有配置文件相關聯,但不提前由D2提取?我不想問數據庫整個配置文件實體。

$profile = $this->getProfileRepository()->find(2); //I want to avoid this 
    $item = new \Alden\BonBundle\Entity\ProfileContact(); 
    $item->setProfile($profile); 
    $item->setDescription('abc'); 
    $em = $this->getEntityManager(); 
    $em->persist($item); 
    $em->flush(); 

回答

2

試試這個

$item->setProfile($em->getReference('Profile', 2));