2012-06-01 135 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));