在 symfony2 中使用外键插入对象的最佳实践 [英] Best practice for inserting objects with foreign keys in symfony2

查看:17
本文介绍了在 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.

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

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 来获取对类别实体的引用,而无需从数据库中加载它.像这样

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('YourProjectEntityCategory', $categoryId);
$product = new Product();
$product->setCategory($category);

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

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