简体   繁体   中英

How i persist data with @ManyToMany Symfony4

I have problem when I want import data (csv) officer with relation ManyToMany Department : the officer (agent in french) are store but the relation are not created (table agent_departement). Agent class :

/**
 * @ORM\Entity(repositoryClass="App\Repository\AgentRepository")
 */
class Agent 
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * 
     */
    private $id;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Departement", inversedBy="agents")
     * @ORM\JoinTable(name="agent_departement")
     */
    private $departements;

public function __construct()
    {
        $this->departement = new ArrayCollection();
        $this->incidents = new ArrayCollection();
    }
  /**
     * @return Collection|departement[]
     */
    public function getDepartements(): Collection
    {
        return $this->departements;
    }

    public function addDepartement(departement $departement): self
    {
        if (!$this->departement->contains($departement)) {


            $departement->addAgent($this);
            $this->departement[] = $departement;
        }

        return $this;
    }

    public function removeDepartement(departement $departement): self
    {
        if ($this->departement->contains($departement)) {
            $this->departement->removeElement($departement);
        }

        return $this;
    }


Class department :

/**
 * @ORM\Entity(repositoryClass="App\Repository\DepartementRepository")
 */
class Departement
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $designation;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Region", inversedBy="departements")
     * @ORM\JoinColumn(nullable=false)
     */
    private $region;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Intervention", mappedBy="departements", orphanRemoval=true)
     */
    private $interventions;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Agent", mappedBy="departements")
     */
    private $agents;


    public function __construct()
    {
        $this->interventions = new ArrayCollection();
        $this->agents = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getDesignation(): ?string
    {
        return $this->designation;
    }

    public function setDesignation(string $designation): self
    {
        $this->designation = $designation;

        return $this;
    }

    public function getRegion(): ?Region
    {
        return $this->region;
    }

    public function setRegion(?Region $region): self
    {
        $this->region = $region;

        return $this;
    }

    /**
     * @return Collection|Intervention[]
     */
    public function getInterventions(): Collection
    {
        return $this->interventions;
    }

    public function addIntervention(Intervention $intervention): self
    {
        if (!$this->interventions->contains($intervention)) {
            $this->interventions[] = $intervention;
            $intervention->setDepartement($this);
        }

        return $this;
    }

    public function removeIntervention(Intervention $intervention): self
    {
        if ($this->interventions->contains($intervention)) {
            $this->interventions->removeElement($intervention);
            // set the owning side to null (unless already changed)
            if ($intervention->getDepartement() === $this) {
                $intervention->setDepartement(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection|Agent[]
     */
    public function getAgents(): Collection
    {
        return $this->agents;
    }

    public function addAgent(Agent $agent): self
    {
        if (!$this->agents->contains($agent)) {
            $this->agents[] = $agent;
            $agent->addDepartement($this);
        }

        return $this;
    }

    public function removeAgent(Agent $agent): self
    {
        if ($this->agents->contains($agent)) {
            $this->agents->removeElement($agent);
            $agent->removeDepartement($this);
        }

        return $this;
    }

}

ImportController

 /**
     * @Route("/agent", name="import_agent")
     */
    public function importAgent(Request $request, DepartementRepository $departementRepository){
        $em = $this->getDoctrine()->getManager();
        $csv = Reader::createFromPath($request->files->get("myfile"), 'r');
        $csv->setDelimiter(';');
        $csv->setHeaderOffset(0); //set the CSV header offset
        $em = $this->getDoctrine()->getManager();
        foreach ($csv as $record) {
            $agent = new Agent();
            $agent->setIdrh($record["Idrh"]);
            $agent->setPoste($record["Poste"]);
            $agent->setPrenom(utf8_encode($record["Prenom"]));
            $agent->setNom(utf8_encode($record["Nom"]));
            $agent->setLibelleRegate($record["Libelle_regate"]);
            $agent->setGrade($record["Grade"]);
            $agent->setEmail($record["Email"]);
            $agent->setRit($record["rit"]);
            $agent->setTelephone($record["Telephone"]);
            $agent->setCodeRegate($record["Code_regate"]);



           $departements = explode(',',$record["Departement"]);
           foreach($departements as $dep){
                $depObject = $departementRepository->find($dep);
                $agent->addDepartement($depObject);

           }

           $em->persist($agent);
           $em->flush();
        }
        return $this->redirectToRoute('agent_index');
    }


The dump duplicate department idk why dump $agent

 +"departement": ArrayCollection^ {#10496 ▼
    -elements: array:8 [▼
      0 => Departement^ {#10584 ▼
        -id: 78
        -designation: "Yvelines"
        -region: Region^ {#10673 ▶}
        -interventions: PersistentCollection^ {#11105 ▶}
        -agents: PersistentCollection^ {#11389 ▶}
      }
      1 => Departement^ {#10584 ▶}
      2 => Departement^ {#11423 ▶}
      3 => Departement^ {#11423 ▶}
      4 => Departement^ {#11436 ▶}
      5 => Departement^ {#11436 ▶}
      6 => Departement^ {#11449 ▶}
      7 => Departement^ {#11449 ▶}
    ]
  }
}

I'm a bit desperate I beat around the bush, thank you for your answers, I hope I was clear and sorry for my poor English

in your addDepartement function you have (and similarly named in other places ...)

$this->departement[] = $departement;

and also the containment check, and also initialization

your property name is quite different though.

private $departements; // <-- plural s

since $this->departement is initialized in the constructor, php will happily work with it, while doctrine doesn't notice any differences on this unmanaged property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM