使用外键将对象插入symfony2的最佳做法 [英] Best practice for inserting objects with foreign keys in symfony2

查看:106
本文介绍了使用外键将对象插入symfony2的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

如果我有动作:

/**
* @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.

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

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?

推荐答案

在ORM中,你必须通过你的实体有关联。您可以使用EntityManager#getReference获取对类实体的引用,而不从DB加载它。
喜欢这个

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

这篇关于使用外键将对象插入symfony2的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆