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

Nic*_*ico 2 doctrine foreign-keys symfony

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

如果我有一个动作:

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

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

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

小智 15

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

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