2011-03-30 14 views
4

我需要assing的值(先前创建的entites Id)的在一个学说2模型来引用列,例如有没有在教条2中使用引用列名的方法?

/** 
* @Entity @Table(name="products") 
*/ 
class product { 

    /** 
    * 
    * @ManyToOne(targetEntity="category") 
    */ 
    protected $category; 

    public function assignCategoryId($id) { 
     $this->category_id=$id; 
    } 


} 

我假定CATEGORY_ID由教义2作为全球化志愿服务青年列名创建, 别不问为什么我要分配id而不是对象本身,因为它必须是这样的。有没有办法做到这一点 ?任何想法 ?

回答

3

虽然@ Orbling的回答是正确的,但实际上并不需要从数据库加载实体。相反,您可以使用参考:

// method on Product entity 
public function setCategory(Category $category) 
{ 
    $this->category = $category; 
} 

// then set the category on the product 
$product->setCategory($entityManager->getReference('category', $categoryId)); 

您可以找到documentation here

+0

好的,这个解决方案听起来不错,但是,因为我尝试在我的项目中实现ddd&cqrs,所以我不想在实体类。我尽量保持我的实体尽可能干净。任何想法? – Orhan 2011-03-30 17:22:34

+0

那么你只使用实体管理器来获取引用,所以你可以使用'$ category = $ entityManager-> getReference('category',$ categoryId);'并将类别传入你的域,而不是categoryId – rojoca 2011-03-30 17:38:26

0

为了做到这一点,您需要创建一个category实体并将其分配给关系属性。

$category = $entityManager->find('category', $categoryID); 

$product = new product(); 
$product->category = $category; 

这将创建我相信的关系。

+0

我想分配的Id已经存在对不起,没有提到。这意味着类别实体是以前创建的。我只想将其ID分配给产品实体。 – Orhan 2011-03-30 10:23:11

+0

在这种情况下,您可以从存储库类加载'category',而不是创建一个新类。 '$ category = $ entityManager-> find('category',$ categoryID);' – Orbling 2011-03-30 10:25:43

相关问题