symfony - 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;
}
}
解决方案
你emailLoginAttempts
实际上是返回数组,LoginAttempts
因为这个 PHP 会给你错误。修复将取决于您的实际逻辑:
- 如果您需要
LoginAttempts
从 - 接收单个实例,emailLoginAttempts
则需要替换getResult()
为getOneOrNullResult()
. - 如果您需要接收具有多个实例的数组
LoginAttempts
- 您需要更新您的方法签名以返回数组:public function emailLoginAttempts($email, $valid_attempts): array
并添加 PHPDoc@return LoginAttempts[]
以便类型信息不会丢失。
推荐阅读
- python - 静态文件不会显示在通过 nginx 提供的实时 django 站点上
- php - 从 wordpress 编辑器将内容作为简码或其他方式插入 php 页面模板
- swift - 如何将类作为函数参数传递?
- vue.js - 在此示例中,如何将样式绑定到我的 v-for 循环?
- apache-kafka - @SentTo 如何将消息发送到相关主题?
- python - 如何从具有多项的python字典中选择值
- javascript - 在 Paypal Javascript 上创建订单时出现问题
- git - 如何解决分支不分开的问题
- servicenow - 如何删除或更换 ServiceNow recordWatch?
- php - php Carbon自定义时间范围及判断是否过期