Doctrine2 - 持有关联实体而不提取关联实体

时间:2012-06-01 09:06:38

标签: symfony doctrine-orm

我有2个实体:ProfileContact和Profile。他们之间有联系。

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实体。

    $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();

1 个答案:

答案 0 :(得分:2)

试试这个

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