1

I'm working on Symfony2, using Doctrine2. My problem is that when I save an array collection with keys, the moment I retrieve them, the keys are the usual 0 to n array index keys, not the ones I put in.

This is my entity:

 /**
 * @var array
 * @ORM\OneToMany(targetEntity="SubEntity", mappedBy="idEntity", cascade={"persist"}, indexBy="idSubEntity")
 */
protected $arraySubEntities;

/**
* @param array() $subEntitiesArray     Simple array with "SubEntity" objects
*
*/
public function __construct($subEntitiesArray)
{
    $this->arraySubEntities = new ArrayCollection;

    foreach ($subEntitiesArray as $subEntity){
        $subEntity->setIdEntity($this);
        $this->addArraySubEntities($subEntity->getIdSubEntityType()->getId(), $subEntity);
    }


public function addArraySubEntities($key, \project\Entity\SubEntityBD $subEntity)
{
    $this->arraySubEntities->set($key, $subEntity);

    return $this;
}

public function getArraySubEntities()
{
    return $this->arraySubEntities;
}

This is the "save" part:

$subEntityTypes = $this->em->getRepository('projectBundle:SubEntityType')->findAll();

$subEntitiesArray = array();
foreach ($subEntityTypes as $subEntityType) {
    $subEntitiesArray[] = new SubEntity($subEntityType);
}

$entity = new Entity($subEntitiesArray);
var_dump($entity);

The 'var_dump()' at the end shows my entity with the correct keys, correct classes, everything is right.

The problem:

$entity = $this->em->getRepository('projectBundle:Entity')->find($idEntity);

$subEntitiesArray = $entity->getArraySubEntities();
var_dump($subEntitiesArray);

This last 'var_dump()' shows the same array, but with 0 to N keys.

By the way, I want my entity to have an array collection with all the subEntities it is related to, and indexed by the type of subEntity they are. As I said, it works fine on the first step, but when I retrieve the arrayCollection from the entity it has lost all it's keys. I did a 'var_dump()' from the entity it self after retrieving it and the array keys are 0 to N too.

Thanks in advance, Cheers.

SOLVED: looks like what I retrieve is just a new formed array, thats why the keys I had are lost.

Joseph
  • 11
  • 4
  • Doctrine owns the collection object and does not know how to set your keys the way you want them. Especially for data retrieval. See if indexBy fits your use case: http://doctrine-orm.readthedocs.org/en/latest/tutorials/working-with-indexed-associations.html. If not then you might be out of luck. – Cerad Apr 29 '15 at 12:18
  • Also understand that when doctine retrieves an entity from the database, the constructor is never called. – Cerad Apr 29 '15 at 12:20
  • Thanks Cerad. I think I got it, the array collection is just an utillity used to save the entity and relate it to the subEntities, not like I'm saving the array itself, just using it until I'm finished saving. I'll try to edit the "get" function to reconstruct the array before I retrieve it. – Joseph Apr 29 '15 at 12:51

0 Answers0