I'm building a API
where I register animals and colors and get animals in return, I'm using Doctrine
to treat entities and I've created a many-to-many relationship between animals and colors.
/**
* @Entity @Table(name="Animais")
**/
class animais {
/**
* @var int
* @Id @Column(type="integer") @GeneratedValue
*/
public $id;
/**
* @var char
* @Column(type="string")
*/
public $sexo;
/**
* @var char
* @Column(type="string")
*/
public $tamanho;
/**
* @var char
* @Column(type="string")
*/
public $tipo_animal;
/**
* @var string
* @Column(type="string") @GeneratedValue
*/
public $coordenada;
/**
* @var string
* @Column(type="string")
* @GeneratedValue
*/
public $obs;
/**
* @var temascores
* @ManyToMany(targetEntity="Cores", inversedBy="animais")
*/
public $cores;
public function __construct()
{
$this->cores = new ArrayCollection();
}
Colors class
/**
* @Entity @Table(name="Cores")
**/
class cores {
/**
* @var int
* @id @Column(type="integer") @GeneratedValue
*/
public $id;
/**
* @var string
* @Column(type="string")
*/
public $cor;
/**
* @var string
* @ManyToMany(targetEntity="Animais", mappedBy="cores")
*/
public $animais;
public function __construct() {
$this->animais = new \Doctrine\Common\Collections\ArrayCollection();
}
The real problem of the application is when I'm going to make a get
of animals, it returns a json
perfect except colors
{
"id": 2,
"sexo": "macho",
"tamanho": "grande",
"tipo_animal": "gato",
"coordenada": "12340-12303",
"obs": "achado ao lado",
"cores": {}
}
I would like the colors to be contained in json
since I already confirmed that they exist in the class when I search for them by EntityManager
method code of API
$app->get('/animal', function (Request $request, Response $response) use ($app) {
$entityManager = $this->get('em');
$animaisRepository = $entityManager->getRepository('App\Models\Entity\Animais');
$animais = $animaisRepository->findOneById(2);
$return = $response->withJson($animais, 200)
->withHeader('Content-type', 'application/json');
return json_encode($animais);
});