0

使用 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和否""

不得不根据它们是否是强制性的(有时是发送"",有时是NULL)来不同地管理数据的发送,这将是一种耻辱并且非常非常乏味。

4

1 回答 1

0

声明你的属性可以为空:

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
}
于 2021-01-03T11:50:06.057 回答