0
I have two tables Plate and Candidate with similar structure:
TABLE Chapa (
id INT AUTO_INCREMENT NOT NULL,
PRIMARY KEY(id)
)
TABLE Candidato (
id INT AUTO_INCREMENT NOT NULL,
chapa_id INT DEFAULT NULL,
PRIMARY KEY(id)
)
And their respective entities:
<?php
use Doctrine\Common\Collections\ArrayCollection;
/** @Entity */
class Chapa
{
// ...
/**
* Uma Chapa possui Muitos Candidatos.
* @OneToMany(targetEntity="Candidato", mappedBy="chapa")
*/
private $candidatos;
// ...
public function __construct() {
$this->candidatos = new ArrayCollection();
}
}
/** @Entity */
class Candidato
{
// ...
/**
* Muitos Candidaatos possuem Uma Chapa.
* @ManyToOne(targetEntity="Chapa", inversedBy="candidatos")
* @JoinColumn(name="chapa_id", referencedColumnName="id")
*/
private $chapa;
// ...
}
With the following queryBuilder I get the result:
$qb = $this->createQueryBuilder('ch')
->select('ch.numero, cds.nome' )
->leftJoin('ch.candidatos', 'cds')
->getQuery()
->getResult();
// Resultado
{
"data": [
{
"numero": "Chapa 10",
"nome": "Candidato 1"
},
{
"numero": "Chapa 10",
"nome": "Candidato 2"
}
],
"success": true
}
How to proceed to receive the following result (nested)?
{
"data": [
{
"numero": "Chapa 10",
"candidatos": [
{
"nome": "Candidato 1"
},
{
"nome": "Candidato 2"
}
]
}
],
"success": true
}
The result you are showing me seems to be generated by another layer in your application. Could show us the code snippet that receives the return from the bank and processes to generate this JSON?
– jlHertel
Of course it is not the Doctrine that returns the JSON. There is an HTTP Responsebag class that converts the return of Doctrine to JSON, keeping the original structure returned from the database. I solved the problem by returning the Doctrine result as array and iterating over it to organize it in the expected way. My question was whether the Doctrine per se could already return in this format, based on the current relationship of the two entities.
– Phelipe Balisa Folgierini
Yes, Doctrine manages to return in the correct format you are expecting, so I wondered how is built the layer that transforms into JSON.
– jlHertel