为什么我收到“这个值应该是字符串类型"?在 Symfony 5 上使用 DateTime 约束时? [英] Why do I receive "This value should be of type string" when using a DateTime constraint on Symfony 5?
本文介绍了为什么我收到“这个值应该是字符串类型"?在 Symfony 5 上使用 DateTime 约束时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下实体(只附上相关部分):
I have the following entity (only attached the relevant parts):
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ApiResource(mercure=true)
* @ORM\Entity(repositoryClass="App\Repository\EventRepository")
*/
class Event {
/**
* @ORM\Column(type="datetime")
* @Assert\DateTime
* @Assert\NotNull
*/
private $createdAt;
public function __construct() {
$this->createdAt = new \DateTime();
}
public function getCreatedAt(): ?\DateTimeInterface {
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self {
$this->createdAt = $createdAt;
return $this;
}
}
它的存储库:
class EventRepository extends ServiceEntityRepository {
public function __construct(ManagerRegistry $registry) {
parent::__construct($registry, Event::class);
}
}
向事件端点(通过 Postman 或 Swagger UI)创建 POST 请求时,它失败并出现以下异常:
When creating a POST request to the event endpoint (via Postman or the Swagger UI), it fails with the following exception:
推荐答案
您使用了错误的断言.
Date
期望一个字符串或一个对象被转换成字符串.而 DateTimeInterface
两者都不是.
Date
expects a string or an object that can be cast into a string. And a DateTimeInterface
is neither.
您应该使用 Type
约束一>.
/**
* @Assert\Type("\DateTimeInterface")
*/
private $createdAt;
使用 Assert\Date
验证 DateTime
对象的能力在 Symfony 4.2 和 在 Symfony 5.0 上它被完全删除.
The ability to use Assert\Date
to validate DateTime
objects was deprecated on Symfony 4.2, and on Symfony 5.0 it was removed altogether.
这篇关于为什么我收到“这个值应该是字符串类型"?在 Symfony 5 上使用 DateTime 约束时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文