Best practice for inserting objects with foreign k

2019-04-12 22:27发布

问题:

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);