我尝试选择操作表中不存在的用户。
<?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();
}
通过转储查看结果,我的User实体中有2种情况:
array:2 [▼
0 => User {#670 ▶}
1 => User {#3280 ▶}
]
在我的Action实体中只有一个:
array:1 [▼
0 => User {#3280 ▶}
]
因此,我应该获得以下结果:
array:1 [▼
0 => User {#670 ▶}
]
但是我只能得到一个空结果:
[]
通过在我的“ getDQL”上进行转储,我得到了对我来说似乎很好的请求(我没有显示任何错误):
"SELECT u FROM App\Entity\User u WHERE NOT(EXISTS(SELECT z FROM App\Entity\User z INNER JOIN z.actions act))"
除了我的成绩,一切都看起来不错!
谢谢您的帮助。
答案 0 :(得分:1)
您已经忘记将用户u和用户z与他们的ID一起加入。
您的DQL应该是:
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
)
)
您的DQL中缺少 WHERE u.id = z.id
因此,您应该在子查询上调用where函数。
/**
* @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();
}