【问题标题】:How to set the id of a foreign key id?如何设置外键id的id?
【发布时间】:2012-10-04 13:29:23
【问题描述】:

根据这篇文章: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.

但从上一次更新的学说2.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.

【问题讨论】:

    标签: php doctrine-orm


    【解决方案1】:

    我已经找到了这个问题的解决方案。

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

    但有时使用对象 id 代替对象更方便,例如当我们在会话中存储标识符时(例如:user_id、site_id、current_process_id、...)。

    在这种情况下,我们应该使用代理,我将参考 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);
    

    希望它能帮助其他人。

    【讨论】:

    • 谢谢,今天这对我有帮助:D
    • 最后一行必须是:$item->setItemType($itemType);
    猜你喜欢
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 2016-05-13
    • 2020-07-15
    相关资源
    最近更新 更多