Created
April 25, 2018 21:13
-
-
Save ricardosaraiva/f1ed59d278fe73f35e4c586072907a3a to your computer and use it in GitHub Desktop.
Doctrine Seriealize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @ORM\Entity() | |
* @ORM\Table(name="clientes") | |
*/ | |
Class Clientes implements \JsonSerializable { | |
/** | |
* @var integer | |
* @ORM\Id() | |
* @ORM\GeneratedValue(strategy="AUTO") | |
*/ | |
private $id; | |
/** | |
* @var string | |
* @ORM\Column(type="string") | |
*/ | |
private $nome; | |
/** | |
* @var ArrayCollection|ImportacaoItem[] | |
* @ORM\OneToMany(targetEntity="Endereco", mappedBy="cliente") | |
*/ | |
private $enderecos; | |
public function __construct() { | |
$this->enderecos = new ArrayCollection(); | |
} | |
public function jsonSerialize() | |
{ | |
return [ | |
'id' => $this->id, | |
'nome' => $this->nome, | |
'enderecos' => $this->enderecos->toArray() | |
]; | |
} | |
} | |
/** | |
* @ORM\Entity() | |
* @ORM\Table(name="enderecos") | |
*/ | |
Class Endereco implements \JsonSerializable { | |
/** | |
* @var integer | |
* @ORM\Id() | |
* @ORM\GeneratedValue(strategy="AUTO") | |
*/ | |
private $id; | |
/** | |
* @var string | |
* @ORM\Column(type="string", name="id_endereco") | |
*/ | |
private $idEndereco; | |
/** | |
* @var string | |
* @ORM\Column(type="string") | |
*/ | |
private $endereco; | |
/** | |
* @var string | |
* @ORM\ManyToOne(targetEntity="Cliente", inversedBy="enderecos") | |
* @ORM\JoinColumn(name="id_endereco", referencedColumnName="id") | |
*/ | |
private $enderecos; | |
public function jsonSerialize() | |
{ | |
return [ | |
'endereco' => $this->endereco | |
]; | |
} | |
} | |
$em = Doctrine\ORM\EntityManager::create($dbParams,$config); | |
$cliente = $em->getRepository(Cliente::class)->find(1); | |
echo json_encode($cliente); //ex: {"id" : 1, "nome" : "Fulano de tal", "enderecos" : [{"endereco" : "Rua xxx"}, {"endereco" : "Rua yyy"}]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment