如何设置外键id的id?

Yon*_*lyo 3 php doctrine-orm

基于这篇文章:如何设置外键id#sf2#doctrine2的id

在上一篇文章中我找到了这个解决方案

class Item
{
/**
 * @ORM\ManyToOne(targetEntity="MyBundle\Entity\ItemType", inversedBy="itemTypes")
 * @ORM\JoinColumn(name="type_id", referencedColumnName="id")
 */
protected $item_type;
/**
 * 
 * @var string $item_type_id
 * @ORM\Column(type="integer")
 */
protected $item_type_id;
}
.... Setter & Getter
}
Run Code Online (Sandbox Code Playgroud)

这让我可以做那样的事情

$item = new Item();
$item->setItemTypeId(2); // Assuming that the ItemType with id 2 exists.
Run Code Online (Sandbox Code Playgroud)

但是从上一次更新doctrine2.3开始,它就不再适用了.

当我持久化项目(因此创建INSERT SQL查询)时,它不会设置item_type_id字段.只有所有其他领域.

知道如何在设置之前手动设置item_type_id而不检索ItemType吗?它过度使用了查询!

$item = new Item();
$itemType = $this->entity_manager->getRepository('Acme\MyBundle:ItemType')->find(2);
$item->setItemType($itemType); // Assuming that the ItemType with id 2 exists.
Run Code Online (Sandbox Code Playgroud)

Yon*_*lyo 10

我找到了这个问题的解决方案.

当我们使用ORM时,我们通常不使用元素的标识符,只使用对象本身.

但有时使用对象id而不是对象是方便的,例如当我们在会话中存储标识符时(例如:user_id,site_id,current_process_id,...).

在这种情况下,我们应该使用Proxies,我将参考Doctrine文档以获取更多信息:http: //docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/advanced-configuration.html #参考代理

在这个例子中,我们将有这样的事情:

$itemTypeId = 2; // i.e. a valid identifier for ItemType
$itemType = $em->getReference('MyProject\Model\ItemType', $itemTypeId);
$item->setItemType($itemType);
Run Code Online (Sandbox Code Playgroud)

希望它会帮助别人.