如何使用 Api-Platform 保存空数据?

问题描述

使用 Symfony 5.1 和 Api Platform,我无法有效处理保存 NULL 数据。

这个简单实体的例子:

class Foo
{
    /**
     * @var string
     *
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */
    public $name;

    /**
     * @var string
     *
     * @ORM\Column(type="text",nullable=true)
     */
    public $content;
}

示例 1(POST 请求):

{
  "name": "","content": ""
}

我同意,这是很好的回报 (ConstraintViolationList) :

{
  "@context": "/api/contexts/ConstraintViolationList",...
  "violations": [
    {
      "propertyPath": "name","message": "This value should not be blank."
    }
  ]
}

示例 2(POST 请求):

{
  "name": "test","content": ""
}

数据库中的注册进展顺利。在数据库中,对于 content 值,我有 ""但我想保存NULL

所以我知道 Api 平台不知道如何将空数据 ("") 转换为 NULL 数据,就像 Symfony 在提交空表单后一样。

所以我再次尝试示例 1,但使用 NULL 数据,以确保 Asserts 仍然有效。

{
  "name": null,"content": null
}

它不起作用,我没有出现 ConstraintViolationList 错误

{
  "@context": "/api/contexts/Error",...
  "hydra:description": "The type of the "name" attribute must be "string","NULL" given.",}

那么我如何处理空数据,以便如果它是空的和强制性的,我有一个错误列表(ConstraintViolationList),但如果它是可选的,那么数据注册NULL 而没有 {{1 }} ?

必须根据数据的发送是否强制(有时发送 "",有时 "")来管理不同的数据发送,这将是一种耻辱,而且非常非常乏味。

解决方法

声明你的属性可以为空:

class Foo
{
    /**
     * @var null|string
     *
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */
    public $name; // php < 7.4 style

    /**
     *
     * @ORM\Column(type="text",nullable=true)
     */
    public ?string $content;  // php >= 7.4 style
}