Whenever I use an ArrayCollection with Doctrine ORM (2.3, PHP > 5.4), and associate the object values with a key in the collection (such as when using the set
method), the values get stored correctly in the database. But when I want to retrieve the collection from the entity, the keys don't get retrieved and instead they use a numeric index.
For instance, 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 properly, but when I retrieve the information the keys in $myArray
are gone.
How do I make the ORM remember properly the keys? Thank you beforehand.
This is solved in the following way:
You also need
MyOtherTable_Key
in your db schema so it can store the key properly.Remember to always set the object key into the property. One way to do so is to declare the key in the constructor.