Doctrine - how to check if a collection contains an entity

mleko picture mleko · Mar 28, 2017 · Viewed 7.5k times · Source

I have two entities User and Article with many-to-many relation as Article can have many authors.

class User
{
    /** @var string */
    public $name;

    /** @var Collection<Article> */
    public $articles;
}

class Article
{
    /** @var string */
    public $title;

    /** @var Collection<User> */
    public $authors;
}

How I can find all Articles with specified (co)author using DQL?

Answer

mleko picture mleko · Mar 28, 2017

Use MEMBER OF expression.

Your DQL query could like like

SELECT art FROM Article art WHERE :user MEMBER OF art.authors

or using query builder

$queryBuilder = $repository->createQueryBuilder("art");
$queryBuilder->where(":user MEMBER OF art.authors");

Alternatively you can join and filter collection

SELECT art FROM Article art JOIN art.authors aut WHERE aut = :user

or

$queryBuilder = $repository->createQueryBuilder("art");
$queryBuilder->join("art.authors", "aut");
$queryBuilder->where("aut = :user");