Best practice for inserting objects with foreign keys in symfony2

丶灬走出姿态 提交于 2019-12-06 11:35:51

问题


What should be the best practice to insert a foreign key in an object in symfony2, if i already have the id of the foreign key?

If i have an action:

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

I don't like the idea of retrieving the category from the database.

This also applies if you have ids in session and you want to store them to the object but without retrieving it from the database... so... what should be the best practice for this?


回答1:


In ORM you have to set Foreign key by an object which your entity associated with. You could use EntityManager#getReference to get a reference to category entity without loading it from DB. Like this

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


来源:https://stackoverflow.com/questions/17492844/best-practice-for-inserting-objects-with-foreign-keys-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!