I have a next tables: quiz, question and junction table question_quiz. I have a many-to-many relationship. Insert is working for the tables quiz and questions but I don't understand how insert in junction table.
Entity quiz.
class Quiz
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=191)
*/
private $name;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Question", mappedBy="quiz", cascade={"persist"})
*/
private $questions;
public function __construct()
{
$this->questions = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* @return string|null
*/
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* @return Collection|Question[]
*/
public function getQuestions(): Collection
{
return $this->questions;
}
public function addQuestion(Question $question): self
{
if (!$this->questions->contains($question)) {
$this->questions[] = $question;
$question->addQuiz($this);
}
return $this;
}
public function removeQuestion(Question $question): self
{
if ($this->questions->contains($question)) {
$this->questions->removeElement($question);
$question->removeQuiz($this);
}
return $this;
}
}
Entity question.
class Question
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="text")
*/
private $title;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Quiz", inversedBy="questions")
*/
private $quiz;
public function __construct()
{
$this->quiz = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
/**
* @return Collection|Quiz[]
*/
public function getQuiz(): Collection
{
return $this->quiz;
}
public function addQuiz(Quiz $quiz): self
{
if (!$this->quiz->contains($quiz)) {
$this->quiz[] = $quiz;
}
return $this;
}
public function removeQuiz(Quiz $quiz): self
{
if ($this->quiz->contains($quiz)) {
$this->quiz->removeElement($quiz);
}
return $this;
}
}
Controller code:
$quiz = new Quiz();
$form = $this->get('form.factory')->createNamed('quiz', QuizType::class, $quiz);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($quiz);
$em->flush();
return $this->redirectToRoute('admin');
}
Code in controller is correct and working, but not working for a table of junction. Maybe need doing with join table, but I not sure it that is working for symfony 4. Could you help me, please?