Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the id of a foreign key id?

Based on this post: How to set the id of a foreign key id #sf2 #doctrine2

In the previous post I found this solution

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
}

Which allows me to do something like that

$item = new Item();
$item->setItemTypeId(2); // Assuming that the ItemType with id 2 exists.

But from the last update of doctrine2.3 it's not working anymore.

when I persist the item(so creating the INSERT SQL query), it does not set the item_type_id field. only all other fields.

Any idea how to set manually the item_type_id without retrieve the ItemType just before setting it ? it's quite over use of queries !?

$item = new Item();
$itemType = $this->entity_manager->getRepository('Acme\MyBundle:ItemType')->find(2);
$item->setItemType($itemType); // Assuming that the ItemType with id 2 exists.
like image 210
Yoni Elyo Avatar asked Sep 19 '25 23:09

Yoni Elyo


1 Answers

I've found the solution of this problem.

As we are working with an ORM, we usually do not use the identifier of an element and just work with the object itself.

But sometimes it is convenient to use the object ids instead of the objects, for example when we store an identifier in the session (ex: user_id, site_id, current_process_id,...).

In these circumstances, we should use Proxies, I'll refer to the Doctrine documentation for more information: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/advanced-configuration.html#reference-proxies

In this example we would then have something like this:

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

Hope it will help others.

like image 167
Yoni Elyo Avatar answered Sep 21 '25 14:09

Yoni Elyo