How to set the id of a foreign key id #sf2 #doctrine2

。_饼干妹妹 提交于 2019-12-10 22:17:16

问题


I'm trying to manually set an foreign key id to an object, but didn't find how to do it

class Item
{
    /**
     * @ORM\ManyToOne(targetEntity="MyBundle\Entity\ItemType", inversedBy="itemTypes")
     * @ORM\JoinColumn(name="type_id", referencedColumnName="id")
     */
    protected $item_type;
}

Is there a way to do something link that?

$item = new Item();
$item->setItemTypeId(1); // This generate an error.

Or do i have to do like that ?

$item = new Item();
$type = Repository::RetrieveById(1);
$item->setItemType($type); // This generate an error.

回答1:


This can be done using Reference Proxies, which let you obtain a reference to an entity for which the identifier is known, without loading that entity from the database.

$type = $em->getReference('MyBundle\Entity\ItemType', 1);
$item->setItemType($type);



回答2:


  1. First of all(Do you have relation defined in ItemType Class?):

    inversedBy="item"
    
  2. So Second:

    Repository::RetrieveById(1); // Not valid code for the repository methods
    
  3. Replace this with:

    $type = $this->getDoctrine()->getRepository('ACMEBundle:ItemType')->find(1);
    
  4. And the second usage will be close to documentation.



来源:https://stackoverflow.com/questions/11539789/how-to-set-the-id-of-a-foreign-key-id-sf2-doctrine2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!