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 :

/**
 * @ORMEntity(repositoryClass="AppRepositoryAgentRepository")
 */
class Agent 
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     * 
     */
    private $id;

    /**
     * @ORMManyToMany(targetEntity="AppEntityDepartement", inversedBy="agents")
     * @ORMJoinTable(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 :

/**
 * @ORMEntity(repositoryClass="AppRepositoryDepartementRepository")
 */
class Departement
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

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

    /**
     * @ORMManyToOne(targetEntity="AppEntityRegion", inversedBy="departements")
     * @ORMJoinColumn(nullable=false)
     */
    private $region;

    /**
     * @ORMOneToMany(targetEntity="AppEntityIntervention", mappedBy="departements", orphanRemoval=true)
     */
    private $interventions;

    /**
     * @ORMManyToMany(targetEntity="AppEntityAgent", 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

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *