php - 为什么我在 Symfony 5 上使用 DateTime 约束时会收到“这个值应该是字符串类型”?
问题描述
我有以下实体(仅附上相关部分):
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 请求时,它会失败并出现以下异常:
解决方案
您使用了错误的断言。
Date
期望一个字符串或可以转换为字符串的对象。而 aDateTimeInterface
两者都不是。
您应该使用Type
约束。
/**
* @Assert\Type("\DateTimeInterface")
*/
private $createdAt;
Assert\Date
用于验证对象的能力DateTime
在 Symfony 4.2 上被弃用,在 Symfony 5.0 上它被完全删除。
推荐阅读
- html - 两个输入字段之间的Angular2 +共享验证
- ios - 为什么我的 viewDidLoad 函数在第二次运行时的行为方式不同?
- java - EventLoop#submit() vs #execute() vs Channel#writeAndFlush()
- javascript - 是否可以将所有 `create-react-app` 包脚本提升一个级别?
- r - 使用 tidyr 将宽表更改为长表
- netlogo - NetLogo 中颜色的线性组合
- spring-boot - Spring Cloud API Gateway 路由不起作用
- javascript - 使用 ajax 在 javascript 中使用 json 的数据
- r - reshape2 是否具有等效的 casetovars?
- sql - 对于 Xamarin Forms,是否有用于查询的 REST API,或者我是否必须创建端点?