“此值应为字符串类型。”在Api平台中使用Symfony DateTime约束时

问题描述 投票:0回答:1

我有以下实体(仅附加了相关部分):

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)时,它失败,但以下异常:

profiler

php symfony doctrine-orm api-platform.com
1个回答
0
投票

我相信您使用的是断言错误。

[Date expects a string or an object that can be cast into a stringDateTimeInterface都不是。

您应该使用Type constraint

/**
 * @Assert\Type("\DateTimeInterface")
 */
 private $createdAt;
© www.soinside.com 2019 - 2024. All rights reserved.