Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony/Doctrine ManyToMany in the order the are assigned

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 {
    ...
}
...
like image 592
wawa Avatar asked Jan 23 '15 15:01

wawa


People also ask

What is many to many relationship in Symfony doctrine?

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.

How do I use manytomany with 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.

Can a Symfony doctrine student opt for multiple courses?

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.

What is a many-to-many Association in Symfony?

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.


1 Answers

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;
}
like image 79
Derick F Avatar answered Sep 20 '22 16:09

Derick F