Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/241.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何设置外键id的id?_Php_Doctrine Orm - Fatal编程技术网

Php 如何设置外键id的id?

Php 如何设置外键id的id?,php,doctrine-orm,Php,Doctrine Orm,根据这篇文章: 在上一篇文章中,我找到了这个解决方案 class Item { /** * @ORM\ManyToOne(targetEntity="MyBundle\Entity\ItemType", inversedBy="itemTypes") * @ORM\JoinColumn(name="type_id", referencedColumnName="id") */ protected $item_type; /** * * @var string $item_type_i

根据这篇文章:

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

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
}
这让我可以做类似的事情

$item = new Item();
$item->setItemTypeId(2); // Assuming that the ItemType with id 2 exists.
但是从doctrine2.3的上一次更新来看,它不再工作了

当我持久化该项时(因此创建INSERT SQL查询),它不会设置项类型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.

我找到了这个问题的解决办法

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

但有时使用对象id而不是对象很方便,例如,当我们在会话中存储标识符时(例如:用户id、站点id、当前进程id等)

在这种情况下,我们应该使用代理,我将参考条令文档了解更多信息:

在本例中,我们将有如下内容:

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

希望它能帮助其他人。

谢谢,这对我今天有帮助:最后一行必须是:$item->setItemType($itemType);