为什么我在 Symfony 5 上使用 DateTime 约束时收到 "This value should be of type string"?

Why do I receive "This value should be of type string" when using a DateTime constraint on Symfony 5?

我有以下实体(只附上相关部分):

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),失败并出现以下异常:

你使用了错误的断言。

Dateexpects a string or an object that can be cast into a stringDateTimeInterface 两者都不是。

您应该使用 Type constraint

/**
 * @Assert\Type("\DateTimeInterface")
 */
 private $createdAt;

使用 Assert\Date 验证 DateTime 对象的功能在 Symfony 4.2 上已弃用,on Symfony 5.0 it was removed altogether.