【问题标题】:API Platform, Posting an object with a relation in MongoDBAPI 平台,在 MongoDB 中发布具有关系的对象
【发布时间】:2019-08-28 14:11:08
【问题描述】:

我正在使用 API 平台和 MongoDB 开发 API。 我的资源非常简单,我有一个用户实体与一个名为 UserCompany 的实体存在一对多关系。

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
}

我只是无法发布 UserCompany:

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

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

所以显然我做错了,传递 ID 不是这样做的标准方式。我该怎么做?

【问题讨论】:

    标签: mongodb symfony doctrine api-platform.com


    【解决方案1】:

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

    1、ReferenceOne注解错误,应该是:

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

    而不是

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多