gpt4 book ai didi

php - 如何设置外键id的id?

转载 作者:可可西里 更新时间:2023-11-01 00:06:07 25 4
gpt4 key购买 nike

基于这篇文章:How to set the id of a foreign key id #sf2 #doctrine2

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

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 查询),它没有设置 item_type_id 字段。仅所有其他字段。

知道如何在设置之前不检索 ItemType 的情况下手动设置 item_type_id 吗?它已经过度使用查询了!?

$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 而不是对象更方便,例如当我们在 session 中存储标识符时(例如:user_id、site_id、current_process_id 等)。

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

在这个例子中,我们会有这样的东西:

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

希望对其他人有帮助。

关于php - 如何设置外键id的id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12728365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com