2016-03-14 29 views
2

鉴于已经存在类别的持久对象。如何一个重复使用在新的对象一个一对多的关系,现有的类别时,只有cateories的ID是已知的在Doctrine中使用外键的现有数据库条目

/** @Entity() */ 
class Category { 
    /** 
    * @var string 
    * @\Doctrine\ORM\Mapping\Column(type="string") 
    */ 
    private $name; 
    /** @var string 
    * @\Doctrine\ORM\Mapping\Id() 
    * @\Doctrine\ORM\Mapping\Column(type="string") 
    */ 
    private $id; 

    /** 
    * Category constructor. 
    * @param string $name 
    * @param string $id 
    */ 
    public function __construct($name, $id) 
    { 
     $this->name = $name; 
     $this->id = $id; 
    } 

    /** 
    * @return string 
    */ 
    public function getName() 
    { 
     return $this->name; 
    } 

    /** 
    * @return string 
    */ 
    public function getId() 
    { 
     return $this->id; 
    } 
} 

现在我可以说,两大类ID = 1 - >小说和id = 2 - >英文书。 现在我知道类别的ID,并希望将我的Book对象中的一对多关系保存起来。

/** @Entity() */ 
class Book { 
    /** @var mixed 
    * @\Doctrine\ORM\Mapping\OneToMany() 
    */ 
    private $categories; 
    /** @var string */ 
    private $title; 

    /** 
    * Book constructor. 
    * @param mixed $categories 
    * @param string $title 
    */ 
    public function __construct($categories, $title) 
    { 
     $this->categories = $categories; 
     $this->title  = $title; 
    } 

    /** 
    * @return mixed 
    */ 
    public function getCategories() 
    { 
     return $this->categories; 
    } 

    /** 
    * @return string 
    */ 
    public function getTitle() 
    { 
     return $this->title; 
    } 
} 

是否有可能创建和手引用坚持一本书对象的现有和已持久化的对象从中我也只知道ID?

回答

2

你不能没有至少检索Reference代理实现这一目标:

$categoriesRefs = ['english' => 1, 'fiction' => 2]; 
$categories = []; 

foreach($categoriesRefs as $ref){ 
    $categories[] = $em->getReference('Namespace\Entity\Category', $ref)); 
} 

$book = new Book($categories, 'title'); 

$em->persist($book); 
$em->flush(); 

您可以存储类不获取整个类别的对象。
查看更多about reference proxy