【问题标题】:How to save null data with Api-Platform?如何使用 Api-Platform 保存空数据?
【发布时间】:2021-04-09 04:48:03
【问题描述】:

使用 Symfony 5.1 和 Api 平台,我无法有效地处理保存 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 Platform 不知道如何将空数据 ("") 转换为 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)以不同方式管理数据发送,这将是一种耻辱,非常非常乏味。

【问题讨论】:

  • 你试过@Assert\NotBlank(allowNull=true) 吗?另外:正如 rugolinifr 在他的回答中指出的那样:您必须允许属性为 null,因此请确保您的 getter/setter 支持它。它说“违反约束”的事实意味着您当前询问的问题与您的 @Assert 约束有关。
  • P.s - NotBlank 验证器表示字符串属性的值可能不是 ''。当您发送 "name": null 而不发送 allowNull=true 时,需要一个非空字符串,因此您的约束违规。 allowNull=true 表示该值可能是null 或必须包含字符串字符(但仍可能不是''(空))。

标签: php symfony api-platform.com symfony-validator


【解决方案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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多