简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM