在symfony2中插入带有外键的对象的最佳实践

时间:2013-07-05 15:57:47

标签: symfony doctrine foreign-keys

如果我已经拥有外键的id,那么在symfony2中的对象中插入外键的最佳做法是什么?

如果我有行动:

/**
* @Route("assignCategory/{category}/product/{product}")
*/
public function assignCategory($category, $product)
{
   ...
   // here i should set the category to the existing product
   ...
}

我不喜欢从数据库中检索类别的想法。

如果你在会话中有id并且你想将它们存储到对象但没有从数据库中检索它,那么这也适用...那么......最好的做法是什么?

1 个答案:

答案 0 :(得分:15)

在ORM中,您必须通过实体关联的对象设置外键。您可以使用EntityManager#getReference获取对类别实体的引用,而无需从DB加载它。 喜欢这个

$category = $entityManager->getReference('YourProject\Entity\Category', $categoryId);
$product = new Product();
$product->setCategory($category);