wawa
wawa

Reputation: 5066

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 {
    ...
}
...

Upvotes: 7

Views: 3424

Answers (1)

Derick F
Derick F

Reputation: 2769

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

Upvotes: 5

Related Questions