I have the need of get the array representation of a Doctrine 2 Entity. I found this library
online, and i am using this class for this purpose:
https://github.com/borisguery/bgylibrary/blob/master/library/Bgy/Doctrine/EntitySerializer.php
The thing is that the class work well but the issue is that every attribute of the entity
that is a relation to another entity(many to one) have the value null on every field on the
resulting array.
A real example:
i have the Entity Person:
<?php
namespace Entities;
/**
* @Entity(repositoryClass=”Repositories\PersonRepository”)
*/
class Person
{
/**
* @Id @GeneratedValue
* @Column(type="bigint")
* @var integer
*/
protected $id;
/**
* @Column(type="string", length=32)
* @var string
*/
protected $firstname;
/**
* @Column(type="string", length=32, nullable="true")
* @var string
*/
/**
* @ManyToOne(targetEntity="Gender", cascade={"detach"})
* @JoinColumn(name="gender", referencedColumnName="id")
*/
protected $gender;
And i have one person object stored on the db with gender(id->1 and name->Male).
When i use this class to convert that person object to array, i got this result:
“id”: “1”,
“firstname”: “lh”,
“middlename”: “”,
“lastname”: “kbkjbkl”,
“dob”: {
“date”: “1982-05-25 00:00:00”,
“timezone_type”: 3,
“timezone”: “America/New_York”
},
“home_phone_number”: “8798798”,
“work_phone_number”: “987987”,
“cell_phone_number”: “987987”,
“ssn”: “98798”,
“email”: “kjhlkjlk”,
“gender”: {
“id”: null,
“name”: null
},
“race”: {
“id”: null,
“name”: null
},
“address”: {
“id”: null,
“address_line1”: null,
“address_line2”: null,
“city”: null,
“zip”: null,
“state”: null
},
“marital_status”: {
“id”: null,
“name”: null
}
Notice the highlighted gender value(has nulls). When it should have 1 and Male.
I will really appreciate any help.
I got it. The problem is that when doctrine loads an entity from the db, the relations are not loaded unless you access it. In the point when you access one of the relations, then doctrine executes the query and grab the info. In my case all the relations have null because have never been accessed. This method of loading is called in doctrine as lazy loading.