Я делал это несколько раз, но это приложение больше сложнее, чем другие, которые я придумал.
Мое приложение представляет собой серверную часть журнала для написания контента. Для упрощения предположим, что содержимое может быть статьей, группировкой (группой содержимого) или диапорамой (слайд-шоу).
Что усложняется, так это то, что все содержимое имеет несколько общих полей. , все объекты содержимого связаны с материнским объектом GlobalContent отношением oneToOne.
Каждый контент (кроме Groupement) может быть связан с 0-n Groupement. Итак, если вы поняли, GlobalContent имеет два групповых отношения: GlobalContent может БЫТЬ групповым элементом (отношение OneToOne, допускающее значение NULL), а GlobalContent может ПРИНАДЛЕЖАТЬ 0-n Groupement
(Для упрощения, поскольку каждый объект связан с одним объектом GlobalContent, я назову два объекта одним именем. Пример: GlobalContent-Article)
Таким образом, статья GlobalContent «Конкурс по поеданию пирогов этим летом» связана с GlobalContent-Groupement «Веселые развлечения этим летом» (которая связана с несколькими другими контентами, связанными с несколькими другими GlobalContent-Groupement). Но эта статья GlobalContent также связана с другой группой GlobalContent, которая связана с другим контентом и т. д.
Код: Выделить всё
GlobalContent Entity
Код: Выделить всё
namespace App\Entity;
use App\Entity\User;
use App\Entity\MiniSite;
use Doctrine\ORM\Mapping as ORM;
use PhpParser\Node\Expr\Cast\Bool_;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\MaxDepth;
#[ORM\Entity(repositoryClass: 'App\Repository\GlobalContentRepository')]
#[ORM\HasLifecycleCallbacks]
class GlobalContent
{
use Timestamps;
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
#[Groups(['read:contents'])]
private $id;
#[ORM\Column(type: 'string', length: 255)]
#[Groups(['read:contents'])]
private $main_titre;
#[ORM\Column(type: 'datetime', nullable: true)]
#[Groups(['read:contents'])]
private $date_publication;
#[ORM\Column(type: 'datetime', nullable: true)]
#[Groups(['read:contents'])]
private $date_maj;
#[ORM\OneToOne(targetEntity: 'App\Entity\Article', mappedBy: 'global_content', cascade: ['persist', 'remove'])]
#[ORM\JoinColumn(nullable: true)]
#[Groups(['read:contents'])]
private $article;
#[ORM\OneToOne(targetEntity: 'App\Entity\Diaporama', mappedBy: 'global_content', cascade: ['persist', 'remove'])]
#[ORM\JoinColumn(nullable: true)]
#[Groups(['read:contents'])]
private $diaporama;
#[ORM\OneToOne(targetEntity: 'App\Entity\Groupement', mappedBy: 'global_content', cascade: ['persist', 'remove'])]
#[ORM\JoinColumn(nullable: true)]
#[Groups(['read:contents'])]
#[MaxDepth(1)]
private $groupement;
#[ORM\JoinTable(name: 'global_content_groupement')]
#[ORM\ManyToMany(targetEntity: 'App\Entity\Groupement', inversedBy: 'all_global_contents')]
#[Groups(['read:contents'])]
#[MaxDepth(1)]
private $all_groupements;
#[ORM\ManyToOne(targetEntity: Theme::class)]
#[ORM\JoinColumn(nullable: true)]
#[Groups(['read:contents'])]
private $mainTheme;
#[ORM\ManyToOne(targetEntity: 'App\Entity\Image')]
#[Groups(['read:contents'])]
private $image;
#[ORM\Column(type: 'json', nullable: true)]
private $published = null;
public function __construct()
{
$this->all_groupements = new ArrayCollection();
}
public function __toString()
{
return $this->main_titre;
}
public function getId(): ?int
{
return $this->id;
}
public function getMainTitre(): ?string
{
return $this->main_titre;
}
public function setMainTitre(string $main_titre): self
{
$this->main_titre = $main_titre;
return $this;
}
public function getDatePublication(): ?\DateTimeInterface
{
return $this->date_publication;
}
public function setDatePublication(\DateTimeInterface $date_publication): self
{
$this->date_publication = $date_publication;
return $this;
}
public function getDateMaj(): ?\DateTimeInterface
{
return $this->date_maj;
}
public function setDateMaj(?\DateTimeInterface $date_maj): self
{
$this->date_maj = $date_maj;
return $this;
}
public function getArticle(): ?Article
{
return $this->article;
}
public function setArticle(?Article $article): self
{
$this->article = $article;
// set the owning side of the relation if necessary
if ($article->getGlobalContent() !== $this) {
$article->setGlobalContent($this);
}
return $this;
}
public function getDiaporama(): ?Diaporama
{
return $this->diaporama;
}
public function setDiaporama(?Diaporama $diaporama): self
{
$this->diaporama = $diaporama;
return $this;
}
public function getGroupement(): ?Groupement
{
return $this->groupement;
}
public function setGroupement(?Groupement $groupement): self
{
$this->groupement = $groupement;
return $this;
}
/**
* @return Collection|Groupement[]
*/
public function getAllGroupements(): Collection
{
return $this->all_groupements;
}
public function addAllGroupement(Groupement $groupement): self
{
// $groupement->addGlobalContent($this); // synchronously updating inverse side
if (!$this->all_groupements->contains($groupement)) {
$this->all_groupements[] = $groupement;
}
return $this;
}
public function removeAllGroupement(Groupement $groupement): self
{
if ($this->all_groupements->contains($groupement)) {
$this->all_groupements->removeElement($groupement);
}
return $this;
}
public function getMainTheme(): ?Theme
{
return $this->mainTheme;
}
public function setMainTheme(?Theme $mainTheme): self
{
$this->mainTheme = $mainTheme;
return $this;
}
public function getImage(): ?Image
{
return $this->image;
}
public function setImage(?Image $image): self
{
$this->image = $image;
return $this;
}
public function getPublished(): ?array
{
return $this->published;
}
public function setPublished(?array $published): self
{
$this->published = $published;
return $this;
}
public function getType(): string
{
if(!is_null($this->getArticle())){
$type = "Article";
} else if(!is_null($this->getDiaporama())){
$type = "Diaporama";
} else if(!is_null($this->getGroupement())){
$type = "Groupement";
} else{
$type = "Inconnu";
}
return $type;
}
public function getSlugType(): string
{
if($this->getType() == "Article"){
$slug = "article";
} else if($this->getType() == "Diaporama"){
$slug = "diaporama";
} else if($this->getType() == "Groupement"){
$slug = "groupement";
} else{
$slug = "inconnu";
}
return $slug;
}
}
Код: Выделить всё
Подробнее здесь: [url]https://stackoverflow.com/questions/78696915/get-rid-of-a-circular-reference-on-complex-entities-relations-symfony-6-4[/url]