Search code examples
phpsymfonydoctrinedoctrine-orm

doctrine2 association is not initialized


I have a Class like the following:

/** @Entity **/
class orgGroup{

    //id and stuff...

    /**
     * @Column(type="string")
     **/
    private $name;

    /**
     * @Column(type="string", nullable=true)
     **/
    private $description;

    /**
     * @ManyToOne(targetEntity="orgGroupType", inversedBy="_orgGroups")
     * @JoinColumn(name="_orgGroupType")
     **/

    private $_orgGroupType;

    //...
}

But when i load this Object from my database via

$groups = $em->getRepository("orgGroup")->findAll();

I just get the name correctly but not the _orgGroupType... and i dont know why... OrgGroup is the owner of orgGroupType and its just ONE object and not an array. My Webservice always just says:

{"error":[],"warning":[],"message":[],"data":[{"name":"AdministratorGroup","description":null,"_orgGroupType":{"__ isInitialized __":false}}]}

The result is:

"name":"AdministratorGroup",
"description":null,
"_orgGroupType":{"__ isInitialized __":false}

but should be:

"name":"AdministratorGroup",
"description":"some description",
"_orgGroupType":{name:"test"}

So there are 2 errors... and I have no idea why. All the data is set correctly in the database.

Any Ideas?

EDIT: Here's the missing code of my orgGroupType -entity

/** @Entity **/
class orgGroupType {
    /**
     * @OneToMany(targetEntity="orgGroup", mappedBy="_orgGroupType")
     **/
    private $_orgGroups;

    public function __construct()
    {
        $this->_orgGroups = new ArrayCollection();
    }
}

Solution

  • This looks to me like a lazy-loading-issue. How do you get the data from the object into the Webservice answer?

    Doctrine2 is lazy-loading if you don't configure something else, that means your $groups = $em->getRepository("orgGroup")->findAll(); won't return real orgGroup objects, but Proxy objects (Doctrine Documentation).

    That means a $group object won't have it's description or orgGroupType value until you call $group->getDescription() or $group->getOrgGroupType() (then Doctrine loads them automatically), so you need to do that before writing the data into the JSON-response for the webservice. It won't work if you somehow loop through the object properties without using the getter methods.

    I hope that was the problem :)