Это мое первое приложение Symfony.Я пытаюсь создать менеджер интервенций, поэтому создал три объекта: Intervention
, Comment
и User
.
. Пользователи управляются FOSUserBundle
.
Классы:
Вмешательство
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\InterventionRepository")
*/
class Intervention
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="smallint")
*/
private $num_rue;
/**
* @ORM\Column(type="string", length=255)
*/
private $nom_rue;
/**
* @ORM\Column(type="string", length=5)
*/
private $cp;
/**
* @ORM\Column(type="decimal", precision=12, scale=9, nullable=true)
*/
private $lat;
/**
* @ORM\Column(type="decimal", precision=12, scale=9, nullable=true)
*/
private $longi;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $description;
/**
* @ORM\Column(type="boolean", options={"default":true})
*/
private $statut;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="intervention", orphanRemoval=true)
*/
private $comments;
public function __construct()
{
$this->comments = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getNumRue(): ?int
{
return $this->num_rue;
}
public function setNumRue(int $num_rue): self
{
$this->num_rue = $num_rue;
return $this;
}
public function getNomRue(): ?string
{
return $this->nom_rue;
}
public function setNomRue(string $nom_rue): self
{
$this->nom_rue = $nom_rue;
return $this;
}
public function getCp(): ?string
{
return $this->cp;
}
public function setCp(string $cp): self
{
$this->cp = $cp;
return $this;
}
public function getLat()
{
return $this->lat;
}
public function setLat($lat): self
{
$this->lat = $lat;
return $this;
}
public function getLongi()
{
return $this->longi;
}
public function setLongi($longi): self
{
$this->longi = $longi;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getStatut(): ?bool
{
return $this->statut;
}
public function setStatut(bool $statut): self
{
$this->statut = $statut;
return $this;
}
/**
* @return Collection|Comment[]
*/
public function getComments(): Collection
{
return $this->comments;
}
public function addComment(Comment $comment): self
{
if (!$this->comments->contains($comment)) {
$this->comments[] = $comment;
$comment->setIntervention($this);
}
return $this;
}
public function removeComment(Comment $comment): self
{
if ($this->comments->contains($comment)) {
$this->comments->removeElement($comment);
// set the owning side to null (unless already changed)
if ($comment->getIntervention() === $this) {
$comment->setIntervention(null);
}
}
return $this;
}
}
Комментарий
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\CommentRepository")
*/
class Comment
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="text")
*/
private $text;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Intervention", inversedBy="comments")
* @ORM\JoinColumn(name="intervention_id", referencedColumnName="id")
*/
private $intervention;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="comments")
* @ORM\JoinColumn(name="author_id", referencedColumnName="id")
*/
private $author;
public function getId(): ?int
{
return $this->id;
}
public function getText(): ?string
{
return $this->text;
}
public function setText(string $text): self
{
$this->text = $text;
return $this;
}
public function getIntervention(): ?Intervention
{
return $this->intervention;
}
public function setIntervention(?Intervention $intervention): self
{
$this->intervention = $intervention;
return $this;
}
public function getAuthor(): ?User
{
return $this->author;
}
public function setAuthor(?User $author): self
{
$this->author = $author;
return $this;
}
}
Пользователь
<?php
// src/Entity/User.php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="author")
*/
private $comments;
public function __construct()
{
parent::__construct();
$this->comments = new ArrayCollection();
}
/**
* @return Collection|Comment[]
*/
public function getComments(): Collection
{
return $this->comments;
}
public function addComment(Comment $comment): self
{
if (!$this->comments->contains($comment)) {
$this->comments[] = $comment;
$comment->setAuthor($this);
}
return $this;
}
public function removeComment(Comment $comment): self
{
if ($this->comments->contains($comment)) {
$this->comments->removeElement($comment);
// set the owning side to null (unless already changed)
if ($comment->getAuthor() === $this) {
$comment->setAuthor(null);
}
}
return $this;
}
}
Проблема заключается вкогда я пытаюсь получить доступ к Intervention
с помощью Doctrine, у меня появляется циклическая ссылка.
Я думал, что comments
при вмешательстве возвращает коллекцию пользователей, которая также возвращает comments
...
$repository = $this->getDoctrine()->getRepository(Intervention::class);
$intervention = $repository->findBy(['statut' => 1]);
return $this->json($intervention);
Есть ли у вас какие-либо предложения, чтобы заставить мой код работать, пожалуйста?Спасибо.
Решение:
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
public function getLocations(){
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object, string $format = null, array $context = array()) {
return $object->getId();
});
$serializer = new Serializer(array($normalizer), array($encoder));
$repository = $this->getDoctrine()->getRepository(Intervention::class);
$intervention = $repository->findBy(['statut' => 1]);
$response = new Response($serializer->serialize($intervention, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
Спасибо за вашу помощь.