Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
like image 765
Yoni Elyo Avatar asked Dec 31 '25 01:12

Yoni Elyo


1 Answers

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);
like image 160
matthew Avatar answered Jan 02 '26 15:01

matthew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!