API平台,在MongoDB中发布具有关系的对象

时间:2019-08-28 14:11:08

标签: mongodb symfony doctrine api-platform.com

我正在使用API​​平台和MongoDB开发API。 我的资源非常简单,我有一个与UserUser实体一对多的User实体。

用户集合的配置如下:

/**
 * @ApiResource
 *
 * @ODM\Document
 */
class User
{

/**
 * @ODM\Id(strategy="UUID", type="string")
 */
private $id;

/**
 * @ODM\Field(type="string")
 * @Assert\NotBlank
 */
private $name;

/**
 * @ODM\Field(type="int")
 * @Assert\NotBlank
 */
private $role = 0;

/**
 * @ODM\ReferenceMany(targetDocument="UserCompany", mappedBy="user")
 */
private $companies;

...

UserCompany集合的配置如下:

/**
 * @ApiResource
 *
 * @ODM\Document
 */
class UserCompany
{

/**
 * @ODM\Id(strategy="UUID", type="string")
 */
private $id;

/**
 * @ODM\Field(type="string")
 * @Assert\NotBlank
 */
private $companyId;

/**
 * @ODM\Field(type="int")
 * @Assert\NotBlank
 */
private $companyRole = 0;

/**
 * @ODM\ReferenceOne(targetDocument="User")
 * @Assert\NotBlank
 */
private $user;

测试API,我设法通过以下方式发布用户:

{
  "name": "whatever",
  "role": 0
}

,响应为

{
  "@context": "/api/contexts/User",
  "@id": "/api/users",
  "@type": "hydra:Collection",
  "hydra:member": [
    {
      "@id": "/api/users/ed34add1f16b3484b72442d7ba8b9fcb",
      "@type": "User",
      "id": "ed34add1f16b3484b72442d7ba8b9fcb",
      "name": "whatever",
      "role": 0
    }
  ],
  "hydra:totalItems": 1
}

我只是无法发布用户公司:

{
  "companyId": "acompany",
  "companyRole": 0,
  "user": "ed34add1f16b3484b72442d7ba8b9fcb"
}

返回一个错误: “无法对用户类型为User的对象进行非规范化,找不到支持的规范化器。”

显然,我做错了,传递ID并不是标准的做法。我该怎么办?

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决方案。上面的代码中有2个错误。

1,ReferenceOne注释错误,应该是:

 * @ODM\ReferenceOne(targetDocument=User::class)

不是

* @ODM\ReferenceOne(targetDocument="User")

第二个帖子中使用的用户参数是

{
  "companyId": "acompany",
  "companyRole": 0,
  "user": "/api/users/ed34add1f16b3484b72442d7ba8b9fcb"
}