2

I'm building an API on Symfony2 an I have a Model ItemOrder with a ManyToOne relationship to a Model Item. I have a few Items in my database, and I want to add an ItemOrder that points to an Item that is already in the database, and whose id I know. So my first approach is this:

$item = new Item();
$item->setId(2);

$orderItem = new OrderItem();
$orderItem->setItem($item);

$em->persist($orderItem);
$em->flush();

However, Symfony2 understand that I'm trying to create a new item. I know that a valid approach would be fetching the Item object with the entity manager, and then assign it to the ItemOrder, but I think it's a not very efficient way of doing it.

So how should this be done?

4

2 回答 2

3

您要查找的内容称为Partial Reference

$item = $em->getPartialReference('Item', 2);

$orderItem = new OrderItem();
$orderItem->setItem($item);

$em->persist($orderItem);
$em->flush();

但是,请阅读 有什么问题?仔细阅读段落,通过 id 查询完整实体可能更安全。

getPartialReference() 与 getReference()

我最初也找到了遗忘的链接,但我认为这不是正确的解决方案。

这两种方法似乎几乎相同,并且都在官方文档中引用。似乎确定哪个最好的唯一合理方法是直接查看源代码:getReference()getPartialReference()

直截了当,您会注意到getPartialReference()通过对与您的用例完全匹配的用例的清晰描述可以更好地记录:

 * The use-cases for partial references involve maintaining bidirectional associations
 * without loading one side of the association or to update an entity without loading it. 

如果您调查代码,getReferece()您会注意到在某些情况下它导致数据库调用:

if ($class->subClasses) {
    return $this->find($entityName, $sortedId);
}

最后,getPartialReference()将部分引用标记为只读,更好地定义它的目的:

$this->unitOfWork->markReadOnly($entity);
于 2013-06-07T10:01:10.413 回答
1

您可以创建特殊的参考对象。有关此问题的更多信息,请参阅

$item = $em->getReference('FQCNBundle:Item', 2);

$orderItem = new OrderItem();
$orderItem->setItem($item);

$em->persist($orderItem);
$em->flush();
于 2013-06-07T11:55:59.550 回答