为什么我收到“此值应为字符串类型"?在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);
}
}
在创建到事件端点的POST请求时(通过Postman或Swagger UI),该请求失败,并带有以下异常:
When creating a POST request to the event endpoint (via Postman or the Swagger UI), it fails with the following exception:
推荐答案
您使用了错误的断言.
Date
期望字符串或可以转换为字符串的对象.而DateTimeInterface
都不是.
您应该使用Type
约束.
/**
* @Assert\Type("\DateTimeInterface")
*/
private $createdAt;
Symfony 4.2和DateTime
对象的功能.在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屋!
查看全文