如何解决如何使用 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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。