我有以下实体(仅附加了相关部分):
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)时,它失败,但以下异常:
我相信您使用的是断言错误。
[Date
expects a string or an object that can be cast into a string。 DateTimeInterface
都不是。
您应该使用Type
constraint。
/**
* @Assert\Type("\DateTimeInterface")
*/
private $createdAt;