Doctrine 2 - ManyToMany + IN clause

2020-07-17 07:58发布

问题:

I've got this model:

/** @Entity @Table(name="articles") */
class Article {
    /** @Id @GeneratedValue @Column(type="integer") */
    protected $id;

    /** @Column(type="string", length=100, nullable=true) */
    protected $title;

    /** @ManyToOne(targetEntity="User", inversedBy="articles") */   
    protected $author;

    /** @Column(type="datetime") */
    protected $datetime;

    /**
     * @ManyToMany(targetEntity="Game", inversedBy="articles")
     * @JoinTable(name="articles_games",
     *      joinColumns={@JoinColumn(name="article_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="game_id", referencedColumnName="id")}
     *      )
     */
    protected $games;

    # Constructor
    public function __construct() {
        $this->datetime = new DateTime();
        $this->games = new \Doctrine\Common\Collections\ArrayCollection();
    }

    # ID
    public function getId() { return $this->id; }

    # TITLE
    public function setTitle($v) { $this->title = $v; }
    public function getTitle() {
        if(empty($this->title)) {
            $game = $this->getFirstGame();
            return ($game instanceof Game) ? $game->getTitle() : NULL;
        } else 
            return $this->title;
    }

    # AUTHOR
    public function setAuthor($v) { $this->author = $v; }
    public function getAuthor() { return $this->author; }

    # DATE & TIME
    public function getDateTime() { return $this->datetime; }
    public function setDateTime($v) { $this->datetime = $v; }

    # GAMES
    public function setGames($value) {
        $except_txt = 'Jedna z przesłanych wartości nie jest instancją klasy Game!';

        if(is_array($value)) {
            foreach($value as $v) {
                if($v instanceof Game) $this->games->add($v);
                else throw new Exception($except_txt);
            }
        } else {
            if($value instanceof Game) $this->games->add($value);
            else throw new Exception($except_txt);
        }
    }
    public function getGames() { return $this->games; }
}

How to make query looking like this

SELECT a FROM Article a WHERE :game_id IN a.games

I have this (the $game->getId() is an integer)

$articles = $db->createQuery("SELECT a.type FROM Article a WHERE :game_id IN a.games GROUP BY a.type")->setParameter('game_id', $game->getId())->getResult();

But it's returning me an syntax error

[Syntax Error] line 0, col 47: Error: Expected Doctrine\ORM\Query\Lexer::T_OPEN_PARENTHESIS, got 'a'

回答1:

If you are looking for articles related to one game:

$articles = $db->createQuery("SELECT a FROM Article a JOIN a.games game WHERE game.id = :game_id")
    ->setParameter('game_id', $game->getId())
    ->getResult();

or multiple:

$articles = $db->createQuery("SELECT a FROM Article a JOIN a.games game WHERE game.id IN (?,?, ... ?)")
    ->setParameters(array($game1->getId(), $game2->getId() ... $gameN->getId()))
    ->getResult();


回答2:

This question was linked from a more recent question that I just answered, and I feel it would also be beneficial to put it here as it is a much more correct solution:

The Doctrine IN function expects a format of (1, 2, 3, 4, ...) after the IN statement. Unfortunately, it is not meant for column conditionals to prove membership.

However, I believe you're looking for the MEMBER OF Doctrine function:

SELECT a FROM Article a WHERE :game_id MEMBER OF a.games

You can pass a valid Doctrine object or the identifier into game_id using this functionality.

The example for this is hidden deep in the Doctrine docs:

$query = $em->createQuery('SELECT u.id FROM CmsUser u WHERE :groupId MEMBER OF u.groups');
$query->setParameter('groupId', $group);
$ids = $query->getResult();


回答3:

I guess you need to create a custom repository for that. I have just solved such problem.

use Doctrine\ORM\EntityRepository;

class Company extends EntityRepository
{
    /**
     * Load by product.
     * @param int $productId
     * @return array
     */
    public function getByProduct($productId)
    {
        $dql = "SELECT i FROM Domain\Model\Company i JOIN i.products p WHERE p.id = :id";
        return $this->_em->createQuery($dql)->setParameter(':id', $productId)->getResult();
    }
}