我陷入了一个几天都解决不了的问题上。正如标题中所说,对于使用MongoDB ODM对嵌入式文档进行部分更新,基于注释的Api平台PUT操作不能像预期的那样工作。
事实上,尽管我尝试了所有不同的配置,但我没有成功地更新已在父文档中设置的嵌入式文档。
我试图更改相关文档中的注释,例如,通过更改规范化和反规范化组,通过尝试不同的嵌入式文档策略,通过为PUT方法设置特定的itemOperations,等等。
我发现的最“有趣”的信息来自Api平台文档中的这一章:https://api-platform.com/docs/core/serialization/#denormalization
“如果@id键存在于嵌入的资源中,那么对应于给定URI的对象将通过数据提供程序检索。嵌入关系中的任何更改也将应用于该对象。”,因此应该检索相应的文档,但它没有。
在embedOne关系中,我有一个父文档Page,其中嵌入了文档Basic。
/**
* @ApiFilter(SearchFilter::class, properties={"basic.name": "ipartial", "basic.title": "exact"})
*
* @ApiResource(
* normalizationContext={"groups"={"read"}},
* denormalizationContext={"groups"={"write"}}
* )
*
* @ODM\Document
*/
class Page
{
/**
* @ODM\Id(strategy="increment", type="integer")
*/
private $id;
/**
* Embedded document with data shared by all Pages and Modules such as name, title, etc.
*
* @Assert\Valid
* @Groups({"read", "write"})
* @ODM\EmbedOne(targetDocument=Basic::class, strategy="set")
*/
private $basic;
}另一方面,我有基本的嵌入式文档:
/**
* @ApiResource()
*
* @ODM\EmbeddedDocument
*/
class Basic
{
/**
* @ApiProperty(identifier=true)
* @Groups({"read", "write"})
* @ODM\Id(strategy="INCREMENT", type="integer")
*/
public $id;
/**
* @Groups({"read", "write"})
* @ODM\Field(type="string")
*/
private $title;
/**
* @Groups({"read", "write"})
* @ODM\Field(type="string")
*/
private $name;
/**
* @Groups({"read", "write"})
* @ODM\Field(type="string")
*/
private $category;
}因此,当我在/api/pages上发出"POST“请求时,如下所示:
{
"basic": {
"title": "Master",
"name": "Peter Jackson",
"category": "Director"
}
}我收到这个201响应:
{
"@context": "\/api\/contexts\/Page",
"@id": "\/api\/pages\/11",
"@type": "Page",
"basic": {
"@id": "\/api\/basics\/21",
"@type": "Basic",
"id": 21,
"title": "Master",
"name": "Peter Jackson",
"category": "Director"
}
}但是我使用这些参数通过api/pages/11对这个资源发出了一个"PUT“请求:
{
"basic": {
"title": "Master",
"name": "Steven Spielberg",
"category": "Director"
}
}我收到了这个200的响应:
{
"@context": "\/api\/contexts\/Page",
"@id": "\/api\/pages\/11",
"@type": "Page",
"basic": {
"@id": "\/api\/basics\/22",
"@type": "Basic",
"id": 22,
"title": "Master",
"name": "Steven Spielberg",
"category": "Director"
}
}正如您所看到的,为PUT操作生成了一个新的基本嵌入式文档,其中使用了请求中设置的值。但我不希望这种情况发生,我希望系统地更新创建的嵌入式文档,因为它已经创建。如果你知道如何处理这件事,非常感谢。干杯!
发布于 2019-08-06 16:20:54
我想这是你的问题。您需要在embedded Relations上设置id,否则将创建它们。
{
"basic": {
"@id": "\/api\/basics\/21",
"title": "Master",
"name": "Steven Spielberg",
"category": "Director"
}
}从文档中:
If an @id key is present in the embedded resource, then the object corresponding to the given URI will be retrieved through the data provider. Any changes in the embedded relation will also be applied to that object.
If no @id key exists, a new object will be created containing data provided in the embedded JSON document.https://stackoverflow.com/questions/57345434
复制相似问题