Search code examples
symfonydoctrine-query

function Doctrine "not exists" doesn't work


I try to select a user that doesn't exist in my action table.

<?php
namespace App\Repository;

use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
* @method User|null find($id, $lockMode = null, $lockVersion = null)
* @method User|null findOneBy(array $criteria, array $orderBy = null)
* @method User[]    findAll()
* @method User[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class UserRepository extends ServiceEntityRepository
{
   public function __construct(RegistryInterface $registry)
   {
       parent::__construct($registry, User::class);
   }

   /**
    * @return User[] Returns an array of User objects
    */
   public function findByCriteres($reqsearch = null)
   {
       $qb = $this->createQueryBuilder('u');

       //Create subquery
       $sub = $this->createQueryBuilder('a');
       $sub = $sub->innerJoin('a.actions', 'act');

        $qb->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())));

        return $qb->getQuery()->getResult();
   }

By doing dump to view the results, I have 2 occurrency in my User entity:

array:2 [▼
  0 => User {#670 ▶}
  1 => User {#3280 ▶}
]

And only one in my Action entity :

array:1 [▼
  0 => User {#3280 ▶}
]

I should therefore obtain the following result:

array:1 [▼
  0 => User {#670 ▶}
]

But I only get an empty result :

[]

By doing a dump on my "getDQL", I get this request which seems good to me (I have no errors displayed):

"SELECT u FROM App\Entity\User u WHERE NOT(EXISTS(SELECT z FROM App\Entity\User z INNER JOIN z.actions act))"

Everything looks good except my result!

Thank you for your help.


Solution

  • You've forgotten to join your sets User u and User z with their ids.

    Your DQL should be:

    SELECT u FROM App\Entity\User u WHERE 
        NOT(
           EXISTS(
               SELECT z FROM App\Entity\User z INNER JOIN z.actions act WHERE u.id = z.id
           )
        )
    

    WHERE u.id = z.id is missing in your DQL

    So your should call where function on your subquery.

    
       /**
        * @return User[] Returns an array of User objects
        */
       public function findByCriteres($reqsearch = null)
       {
           $qb = $this->createQueryBuilder('u');
    
           //Create subquery
           $sub = $this->createQueryBuilder('z');
           $sub = $sub->innerJoin('z.actions', 'act')
                      ->where('z.id = u.id');
    
            $qb->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())));
    
            return $qb->getQuery()->getResult();
       }