What's the issue on my repository function?

449 Views Asked by At

I get the following error when i try to use this in my controller

Return value of App\Repository\AccountRepository::findOneByAccountCode() must be an instance of App\Repository\Bank or null, instance of App\Entity\Account returned

/**
 * @param Request $request
 * @param string $accountCode
 * @return Response
 * @throws EntityNotFoundException
 */
public function somefunction(Request $request, string $accountCode)
{
    /** @var BankRepository $acRepository */
    $acRepository = $this->getDoctrine()->getRepository(Account::class);
    $bank = $acRepository->findOneByAccountCode($accountCode);        
}

Repository Code

public function findOneByAccountCode(string $accountCode): ?Bank
{
    try {
        return $this->createQueryBuilder('a')
            ->innerJoin('a.bank', 'b')
            ->where('a.code = :code')
            ->setParameter('code', $accountCode)
            ->getQuery()
            ->getOneOrNullResult();
    }catch (NonUniqueResultException $e) {
        return null;
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

just changed the code to my AccountRepository and added array as a return type

function findOneByAccountCode(string $accountCode): ?array{
        return $this->createQueryBuilder('a')
            ->innerJoin('a.bank', 'b')
            ->where('a.code = :code')
            ->setParameter('code', $accountCode)
            ->getQuery()
            ->getResults();
    } 

0
On

I think you have just to change return type of

public function findOneByAccountCode(string $accountCode): ?Bank
{
    try {
        return $this->createQueryBuilder('a')
            ->innerJoin('a.bank', 'b')
            ->where('a.code = :code')
            ->setParameter('code', $accountCode)
            ->getQuery()
            ->getOneOrNullResult();
    } catch (NonUniqueResultException $e) {
        return null;
    }
}

from

: ?Bank

to

: ?Account



public function findOneByAccountCode(string $accountCode): ?Account
{
    try {
        return $this->createQueryBuilder('a')
            ->innerJoin('a.bank', 'b')
            ->where('a.code = :code')
            ->setParameter('code', $accountCode)
            ->getQuery()
            ->getOneOrNullResult();
    } catch (NonUniqueResultException $e) {
        return null;
    }
}