Search code examples
phpsymfonydql

How to search an array of an entity in dql?


I am trying to filter out admins that have a super admin role. Why is the following not working?

public function findAdmins()
{
    $qb = $this->getEntityManager()->createQueryBuilder();
    $qb
        ->select('a')
        ->from('MyBundle:Admin', 'a')
        ->where($qb->expr()->notIn('ROLE_SUPER_ADMIN', 'a.roles'));

    $result = $qb->getQuery()->execute();

    return $result;
}

It will give me the following error:

[Syntax Error] line 0, col 68: Error: Expected Literal, got 'a' 

The DQL-query looks like this:

SELECT a FROM MyBundle:Admin a WHERE ROLE_SUPER_ADMIN NOT IN(a.roles)  

Role itself is not an entity. It is simply an array of strings.

$roles = array('ROLE_ADMIN', 'ROLE_SUPER_ADMIN)'

Solution

  • Try use MEMBER OF operator

    $qb
    ->select('a')
    ->from('MyBundle:Admin', 'a')
    ->where(':role NOT MEMBER OF ad.roles')->setParamete('role', 'ROLE_SUPER_ADMIN');
    

    Update. The only solution found is to check serialized string in db with LIKE. Details here