Search code examples
symfonydoctrinecriteria

Symfony Doctrine findOneBy with not equal to


I need to find a phone number in a recording where the contract ID is not equal to current contract ID. It is easy to find in a specific contract ID. $value is the entity instance in my custom validator.

$existingPhone = $this->contractRepository->findOneBy(['phone' => $value->getPhone(), 'contractId' => $value->getContractId()]);

but how to find in other than the current contract ID?


Solution

  • You need to create a method in your contractRepository, and use the Doctrine QB.

            $qb = $this->createQueryBuilder('c');
            $qb
                ->where('c.phone = :phone')
                ->andWhere(
                    $qb->expr()->neq('c.contractId', 'contractId')
                )
                ->setParameters([
                    'phone' => $phone,
                    'contractId' => $contractId,
                ])
                ->setMaxResults(1)
                ->getQuery()
                ->getOneOrNullResult();