Reputation: 1219
I'm am developing an API using API Platform and MongoDB. My resources are very simple, I have a User entity in a one to many relationship with an entity called UserCompany.
The User collection is configured as follow:
/**
* @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;
...
The UserCompany collection is configured as follow:
/**
* @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;
Testing the API, I manage to Post a user with:
{
"name": "whatever",
"role": 0
}
and the response is
{
"@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
}
I just don't manage to Post a UserCompany:
{
"companyId": "acompany",
"companyRole": 0,
"user": "ed34add1f16b3484b72442d7ba8b9fcb"
}
returns me an error: "Could not denormalize object of type User, no supporting normalizer found."
So apparently I'm doing something wrong and passing the ID is not the standart way of doing this. How do I do it ?
Upvotes: 0
Views: 212
Reputation: 1219
OK, I found the solution. There are 2 mistakes in the above code.
1st, the ReferenceOne annotation is wrong, it should be:
* @ODM\ReferenceOne(targetDocument=User::class)
and not
* @ODM\ReferenceOne(targetDocument="User")
2nd the user parameter to use in the post is
{
"companyId": "acompany",
"companyRole": 0,
"user": "/api/users/ed34add1f16b3484b72442d7ba8b9fcb"
}
Upvotes: 0