Сопоставление ассоциаций: manytomany Symfony - PullRequest
2 голосов
/ 03 августа 2020

В настоящее время у меня есть 2 объекта "Посетитель" и "Посещение", и я установил отношения "многие ко многим", но я застрял в том, как узнать, какой объект является владельцем, а какой - нет. все это посещение. Я хочу сделать CRUD двух его объектов для посетителя без проблем, но для объекта посещения там это усложняет. Мне удается отобразить список моих посещений, чтобы прочитать их и удалить, но для редактирования и создания sa не

Я думаю, что в первую очередь У меня есть ошибка, связанная с инвертированием и отображением двух моих объектов.

Но также относительно моего edit и new методы моего VisiteController.

Entity Visite:

<?php
 
****
/**
 * @ORM\Entity(repositoryClass=VisiteRepository::class)
 */
class Visite
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;
 
    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $libelle;
 
     
    /**
     * @ORM\ManyToMany(targetEntity=Personne::class, mappedBy="visite")
     */
    private $personnes;
 
 
    public function __construct()
    {
        $this->personnes = new ArrayCollection();
    }
 
    public function getId(): ?int
    {
        return $this->id;
    }
 
    public function getLibelle(): ?string
    {
        return $this->libelle;
    }
 
    public function setLibelle(?string $libelle): self
    {
        $this->libelle = $libelle;
 
        return $this;
    }
 
    /**
     * @return Collection|Personne[]
     */
    public function getPersonnes(): Collection
    {
        return $this->personnes;
    }
 
    public function addPersonne(Personne $personne): self
    {
        if (!$this->personnes->contains($personne)) {
            $this->personnes[] = $personne;
            $personne->addVisite($this);
        }
 
        return $this;
    }
 
    public function removePersonne(Personne $personne): self
    {
        if ($this->personnes->contains($personne)) {
            $this->personnes->removeElement($personne);
            $personne->removeVisite($this);
        }
 
        return $this;
    }
 
 
}

Entity Personne / Visiteur:

<?php
 
namespace App\Entity;
 
use App\Repository\PersonneRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
 
/**
 * @ORM\Entity(repositoryClass=PersonneRepository::class)
 */
class Personne
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;
 
    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $nom;
 
    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $email;
 
 
    /**
     * @ORM\ManyToMany(targetEntity=Visite::class, inversedBy="personnes")
     */
    private $visite;
 
    public function __construct()
    {
        $this->visite = new ArrayCollection();
    }
 
    public function getId(): ?int
    {
        return $this->id;
    }
 
    public function getNom(): ?string
    {
        return $this->nom;
    }
 
    public function setNom(?string $nom): self
    {
        $this->nom = $nom;
 
        return $this;
    }
 
 
    public function getEmail(): ?string
    {
        return $this->email;
    }
 
    public function setEmail(?string $email): self
    {
        $this->email = $email;
 
        return $this;
    }
 
 
    /**
     * @return Collection|Visite[]
     */
    public function getVisite(): Collection
    {
        return $this->visite;
    }
 
    public function addVisite(Visite $visite): self
    {
        if (!$this->visite->contains($visite)) {
            $this->visite[] = $visite;
        }
 
        return $this;
    }
 
    public function removeVisite(Visite $visite): self
    {
        if ($this->visite->contains($visite)) {
            $this->visite->removeElement($visite);
        }
 
        return $this;
    }
 
}

При создании нового посещения он регистрируется в базы данных, но, к сожалению, это единственная вставка в таблицу посещений, мне нечего добавить в ассоциативную таблицу person_visit.

Контроллер посещения:

/**
     * @Route("/new", name="visite_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $visite = new Visite();
        $form = $this->createForm(VisiteType::class, $visite);
        $form->handleRequest($request);
 
        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($visite);
            $entityManager->flush();
 
            return $this->redirectToRoute('visite_index');
        }
 
        return $this->render('visite/new.html.twig', [
            'visite' => $visite,
            'form' => $form->createView(),
        ]);
    }
 
 
    /**
     * @Route("/{id}/edit", name="visite_edit", methods={"GET","POST"})
     * @param Visite $visite
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function edit(Visite $visite, Request $request)
    {
        $personne = new Personne();
        $visite->addPersonne($personne);
 
        $form = $this->createForm(VisiteType::class, $visite);
        $form->handleRequest($request);
 
        if ($form->isSubmitted() && $form->isValid()) {
/*            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($visite, $personne);
            $entityManager->flush();*/
            $this->getDoctrine()->getManager()->flush();
           /* $this->addFlash('success', 'Visite ajouté avec succès');*/
 
            return $this->redirectToRoute('visite_index');
        }
 
        return $this->render('visite/edit.html.twig', [
            'visite' => $visite,
            'form' => $form->createView(),
        ]);
    }

Чем ks за вашу помощь

...