[英]How to save null data with Api-Platform?
使用 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 平台不知道如何將空數據( ""
)轉換為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.",
}
那么如何處理 null 數據,以便如果它是空的並且是強制性的,我有一個錯誤列表( ConstraintViolationList
),但如果它是可選的,那么數據注冊為NULL
並且沒有""
?
必須根據它們是否是強制性的(有時發送""
,有時發送NULL
)來不同地管理數據的發送,這將是一種恥辱,非常非常乏味。
聲明你的屬性可以為空:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.