Doctrine - Save ArrayCollection

Whenever I use ArrayCollection with ORM (Doingrine ORM) (2.3, PHP> 5.4) and match the values โ€‹โ€‹of the object with the key in the collection (for example, using the set method), the values โ€‹โ€‹are stored correctly in the database, but when I want to extract the collection from the essence, keys are not obtained, and instead they use a numerical index.

For example, if I have the following classes:

 /** @Entity */ class MyEntity { /** @OneToMany(targetEntity="MyOtherEntity", mappedBy="mainEntity") */ private $myArray; public function __construct() { $this->myArray = new ArrayCollection(); } public function addOtherEntity($key, $value) { $this->myArray->set($key, $value); } ... } /** @Entity */ class MyOtherEntity { /** @ManyToOne(targetEntity="MyEntity", inversedBy="myArray") */ private $mainEntity; ... } 

The set method works correctly, but when I retrieve the information, the keys in $myArray gone.

How to make ORM remember keys correctly? Thanks in advance.

+7
source share
1 answer

This is solved as follows:

 /** @Entity */ class MyEntity { /** @OneToMany(targetEntity="MyOtherEntity", mappedBy="mainEntity", indexBy="key") */ private $myArray; public function __construct() { $this->myArray = new ArrayCollection(); } public function addOtherEntity($key, $value) { $this->myArray->set($key, $value); } ... } /** @Entity */ class MyOtherEntity { /** @ManyToOne(targetEntity="MyEntity", inversedBy="myArray") */ private $mainEntity; /** @Column(name="MyOtherTable_Key", type="string", unique=true, length=50) private $key; ... } 

You also need MyOtherTable_Key in your db schema so that it can store the key correctly.

Remember to always set the object key to the property. One way to do this is to declare a key in the constructor.

 public function __construct($key) { $this->key = $key; } 
+5
source

All Articles