I have an entity called Game
which has a ManyToMany
connection with a JoinTable
to an entity called Question
This works pretty well. The problem is, that I need the questions in the exact order as they are chosen, not sorted by question id, as I get them now when I call getQuestions()
on the Game
class.
Is there a way to do that?
The Questions are all added with $game->addQuestion($question);
. The Questions are existing, the game is persisted, after the questions are added.
...
class Game {
...
/**
* @ORM\ManyToMany(targetEntity="Question")
* @ORM\JoinTable(name="Games_to_Questions",
* joinColumns={@ORM\JoinColumn(name="game_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="question_id", referencedColumnName="id")}
* )
**/
private $questions;
...
}
...
class Question {
...
}
...
Symfony Doctrine Many to Many Relationship (ManyToMany) Many to many relations are one of the mostly used relations in the relational database. It took a while for me to figure how to properly configure this relation in Symfony Doctrine.
Even outside of Doctrine, this is how you build a ManyToMany relationship: you create a "join table" that keeps track of which tags are related to which questions. With Doctrine, it's no different... except that Doctrine is going to handle the heavy lifting of inserting and removing records to and from this table for us. We'll see that in a minute.
It took a while for me to figure how to properly configure this relation in Symfony Doctrine. I am sharing this so it might be useful for someone. Used very simple example students and course. A student can opt for multiple courses and a single course can be opted by multiple students.
When working in Symfony and using Doctrine 2 ORM you sometimes need to use a many-to-many association between entities. This relationship means that a blog post can have multiple categories. And categories can be used in multiple blog posts.
you're going to have to add an intermediary entity with a sort order column. Let's call it GameQuestion.
/**
* @ORM\Table(name="game_question")
* @ORM\Entity(repositoryClass="Gedmo\Sortable\Entity\Repository\SortableRepository")
*/
class GameQuestion {
private $game;
private $question;
/**
* @Gedmo\SortablePosition
*/
private $sortOrder;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With