首页 > 解决方案 > Symfony 4 / Doctrine 查询:返回值必须是

问题描述

我的学说查询显然返回了错误的类型,getResult()但我不明白为什么。它说数组返回;这就是我所期待的......

控制器:

public function checkbrute($username, $email ) {

   $repository = $this->getDoctrine()->getRepository(LoginAttempts::class);

   $now = time();
   $valid_attempts = $now - (2 * 60 * 60);

   $attempts = $repository->emailLoginAttempts($email, $valid_attempts);

   return sizeof($attempts);

}

存储库

    public function emailLoginAttempts($email, $valid_attempts): ?LoginAttempts
{
    return $this->createQueryBuilder('l')
        ->select('l.time')
        ->andWhere('l.email = :val')
        ->andWhere('l.time > :val2')
        ->setParameter('val', $email)
        ->setParameter('val2', $valid_attempts)
        ->getQuery()
        ->getResult() //ERROR HERE
    ;
}

错误:

Return value of App\Repository\LoginAttemptsRepository::emailLoginAttempts() must be an instance of App\Entity\LoginAttempts or null, array returned

实体:

<?php

 namespace App\Entity;

 use Doctrine\ORM\Mapping as ORM;
 use Gedmo\Mapping\Annotation;


/**
 * LoginAttempts
 *        @ORM\Entity(repositoryClass="App\Repository\LoginAttemptsRepository")
 * @ORM\Table(name="login_attempts")
 */
class LoginAttempts
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="username", type="string", length=100, nullable=false)
 */
private $username;

/**
 * @var string
 *
 * @ORM\Column(name="email", type="string", length=100, nullable=false)
 */
private $email;

/**
 * @var string
 *
 * @ORM\Column(name="time", type="string", length=100, nullable=false)
 */
private $time;

public function getId(): ?int
{
    return $this->id;
}

public function getUsername(): ?string
{
    return $this->username;
}

public function setUsername(string $username): self
{
    $this->username = $username;

    return $this;
}

public function getEmail(): ?string
{
    return $this->email;
}

public function setEmail(string $email): self
{
    $this->email = $email;

    return $this;
}

public function getTime(): ?string
{
    return $this->time;
}

public function setTime(string $time): self
{
    $this->time = $time;

    return $this;
}


}

标签: symfonydoctrine-orm

解决方案


emailLoginAttempts实际上是返回数组,LoginAttempts因为这个 PHP 会给你错误。修复将取决于您的实际逻辑:

  1. 如果您需要LoginAttempts从 - 接收单个实例,emailLoginAttempts则需要替换getResult()getOneOrNullResult().
  2. 如果您需要接收具有多个实例的数组LoginAttempts- 您需要更新您的方法签名以返回数组:public function emailLoginAttempts($email, $valid_attempts): array并添加 PHPDoc@return LoginAttempts[]以便类型信息不会丢失。

推荐阅读