首页 > 解决方案 > 为什么我在 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 请求时,它会失败并出现以下异常:

剖析器

标签: phpsymfonyapi-platform.comsymfony-validatorsymfony5

解决方案


您使用了错误的断言。

Date 期望一个字符串或可以转换为字符串的对象。而 aDateTimeInterface两者都不是。

您应该使用Type 约束

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

Assert\Date用于验证对象的能力DateTime在 Symfony 4.2 上被弃用,在 Symfony 5.0 上它被完全删除


推荐阅读