Олег Нечаев
Олег Нечаев

Reputation: 69

Doctrine: ManyToMany

I'm a newbie on Synfony2 and doctrine usage. I have created two related entities for a survey. App\Entity\Question:

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

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

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Options", inversedBy="questions")
     */
    private $options;

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

App\Entity\Options:

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

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

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Question", mappedBy="options")
     */
    private $questions;

    public function __construct()
    {
        $this->answers = new ArrayCollection();
        $this->questions = new ArrayCollection();
    }
}

It creates a new table: question_options. Now my MYSQL model looks like: model Now I need to attach question_options table to answer table by answer.question_options_id. How can I do that using Doctrine? I'm confusing because of the absence of question_options entity. I found out that many-to-many connections aren't entities.

Upvotes: 1

Views: 261

Answers (1)

LPodolski
LPodolski

Reputation: 2878

best way would be to attach Option to answer, because question_options table is only an metadata, and user in pool really selects an option. In an sense that user when answering do not select question_option but rather specific option. This looks just weird that answer would gave question option as FK.

or create Many to Many manually, by creating QuestionOption entity class manually, an join in using OneToMany, ManyToOne with Question and Option

this is better option, to make it more open closed for modification, because you can add more fields describing answer if needed like for example time it take to answer, number of changes etc.

I would also recommend to add User suffix for tables/entities that have FK with user because it is now confusing what is user's answer, and what is just general structure of pool.

Upvotes: 1

Related Questions