在symfony 4中以多对多关系插入联结表

时间:2018-08-21 18:25:41

标签: symfony insert doctrine many-to-many junction-table

我还有一个表格:测验问题和联结表 question_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;
}
}

实体问题。

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;
}
}

控制器代码:

$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');
}

控制器中的代码正确且有效,但不适用于联结表。也许需要使用连接表,但我不确定它是否适用于symfony4。请您能帮我吗?

0 个答案:

没有答案