api-platform / core

The server component of API Platform: hypermedia and GraphQL APIs in minutes
https://api-platform.com
MIT License
2.39k stars 848 forks source link

Add elements in a Relation #1794

Closed cduran433 closed 6 years ago

cduran433 commented 6 years ago

I don't know if this is the normal behavior, I have a OnetoMany relation between two class (Competitions and Event). I follow the documentation and I can create elements but I want to add elements to the relation and keep the other ones but I am not able to do it.

Competition Entity

/**
 * Competitions able to request in the unibet API.
 *
 * @ApiResource(
 *              attributes={
 *                  "normalization_context"={"groups"={"read", "write"}},
 *                  "denormalization_context"={"groups"={"read","write"}}
 *              },
 *              collectionOperations={"get", "post"},
 *              itemOperations={"get", "put"}
 *     )
 * @ORM\Entity
 */

class Competition
{
...

    /**
     * @ORM\OneToMany(targetEntity="Event", mappedBy="competitions", cascade={"persist"})
     * @ApiSubresource(maxDepth=1)
     * @Groups({"read","write"})
     */
    public $events;

    public function addEvent(Event $event)
    {
        $event->competition = $this;
        $this->events->add($event);
    }

    public function removeEvent(Event $event)
    {
        $event->competition = null;
        $this->events->removeElement($event);
    }
/**
 * Available event to bet.
 *
 * @ApiResource(
 *              attributes={
 *                  "normalization_context"={"groups"={"read","write"}},
 *                  "denormalization_context"={"groups"={"read","write"}}
 *              },
 *              collectionOperations={"get", "post"},
 *              itemOperations={
 *                  "get","put"}
 *  )
 * @ORM\Entity
 */
class Event
{

....

    /**
     * @ORM\ManyToOne(targetEntity="Competition", inversedBy="events")
     * @Groups({"read","write"})
     */

    public $competitions;

When I send a PUT notification to /competitions/{id}

{
  "unibetId": "Test1",
  "name": "string",
  "sport": "string",
  "events": [
      "/events/38"
  ]

}

It works perfectly, but if after this one I send another request to add other event in the same competition. The last event is removed:

{
  "unibetId": "Test1",
  "name": "string",
  "sport": "string",
  "events": [
      "/events/39"
  ]

}

Right now I only have in the database a relation with event 39. Is it possible to add elements to a relationship without creating a custom controller?

Simperfit commented 6 years ago

You need to keep them in the array when sending a PUT request, no need for a custom controller.