我的存储库功能有什么问题?

时间:2019-10-15 15:01:21

标签: symfony symfony4 symfony-4.2 symfony-4.3

当我尝试在控制器中使用此错误消息

  

的返回值   App \ Repository \ AccountRepository :: findOneByAccountCode()必须是   App \ Repository \ Bank的实例,或者为null,则为   应用\实体\帐户已返回

/**
 * @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);        
}

存储库代码

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 个答案:

答案 0 :(得分:0)

只是将代码更改为我的AccountRepository并添加了数组作为返回类型

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

答案 1 :(得分:0)

我认为您只需更改返回类型

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;
    }
}

来自

: ?Bank

: ?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;
    }
}