Home » Php » php – how to filter a getter in doctrine2 entity?

php – how to filter a getter in doctrine2 entity?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have an entity that has a one-to-many association (many-to-many with extra fields):

class Game {
    /**
    /* @OneToMany(targetEntity="GamePlayer", mappedBy="game", cascade={"persist"})
    /* @JoinColumn(name="id", referencedColumnName="game_id", onDelete="cascade")
     */
    private $gamePlayer;
}

The class has automated getter for all the authors: getGamePlayers()

I would like to add a filter to it, so it would query the database only for the relevant details in the most efficient way:

public function getGamePlayersWithScoreHigherThan($score){
    //what to write here? (return array)
}

What is the best way to achieve such a getter from within the entity (not using the repository)?

Thank you very much!

How to&Answers:

You could try creating a separate method on your entity that uses the Doctrine\Common\Collections\Criteria to filter the associated collection. See this link for details.