Flyzzx
Flyzzx

Reputation: 460

Symfony API create entity with relation to existing entities

I have a Symfony API with two entities : Apartment and User. The apartment entity has a field named owner who is a User object.

private $owner;

I want to create an Appartment linked to the owner with id 8. I send this JSON :

{
"title": "Appartement n°144",
"description": "Description de l'appartement 144",
"rooms": 2,
"area": 11.2,
"price": 101.2,
"visible": true,
"location": {
    "latitude": 0,
    "longitude": 0,
    "altitude": 0
},
"owner": 8

}

I have also tried to change "owner": 8 to "8" or to "owner": {id: "8"}, but I have always this error :

{
"error": {
    "code": 400,
    "message": "Bad Request",
    "exception": [
        {
            "message": "Invalid data \"8\"(integer), expected \"HGB\\CoreBundle\\Entity\\User\".",
            "class": "Symfony\\Component\\HttpKernel\\Exception\\BadRequestHttpException",

If someone has the tips.

Here is my controller :

public function addOneAppartment(Appartment $appartment)
{
    $manager = $this->getDoctrine()->getManager();
    $manager->persist($appartment);
    $manager->flush();

    return $appartment;
}

Upvotes: 0

Views: 276

Answers (1)

Iwan Wijaya
Iwan Wijaya

Reputation: 2157

{id: "8"} should work with JMS, make sure you are using the correct groups.

And make sure to use doctrine object constructor:

services:
    jms_serializer.object_constructor:
        alias: jms_serializer.doctrine_object_constructor

Upvotes: 1

Related Questions