Search code examples
restsymfonyapi-platform.comsymfony-flex

API Platform related entities on resource creation


Is there a way of passing array of ids of already created related entities on entity creation resource? The default docs say about creating everything on post request. Some data. I have Squad entity:

/**
 * @ApiResource(iri="http://schema.org/Squad")
 * @ORM\Table(name="squads")
 * @ORM\Entity()
 */
class Squad
{
    use IdentityAutoStrategy, Timestamps;

    /**
     * @var string
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $name;

    /**
     * @var Collection|User[]|null
     * @ORM\OneToMany(targetEntity="User", mappedBy="squad")
     * @ApiProperty(
     *     attributes={
     *         "swagger_context"={
     *             "$ref"="#/definitions/User",
     *         }
     *     }
     * )
     * @ApiSubresource(max_depth=1)
     */
    private $users;

And User entity:

/**
 * @ApiResource()
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="GPL\Repository\UserRepository")
 */
class User implements UserInterface, Serializable
{
    use Timestamps, IdentityAutoStrategy;

    /**
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=64)
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=254, unique=true)
     */
    private $email;

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    /**
     * @var Squad
     * @ORM\ManyToOne(targetEntity="Squad", inversedBy="users")
     * @ORM\JoinColumn(name="squad_id", referencedColumnName="id")
     * @ApiProperty(
     *     attributes={
     *         "swagger_context"={
     *             "$ref"="#/definitions/Squad",
     *         }
     *     }
     * )
     */
    private $squad;

The main thins I want to achieve is to send POST /api/squads with "users": [1,2,3] where 1, 2, 3 is id of existing users and links them to created Squad entity. Is this available using some default annotations from api-platform? Or how can i do this?


Solution

  • For JSON-LD you can use IRIs like this:

    users: ["users/1", "users/2"]
    

    Keep in mind, that this won't work if you disable GET item operation in your users resource.

    You can also enforce this and disable embedded data to prevent your clients from creating new users by excluding all your user field groups.

    /**
     * @ApiResource(attributes={
     * "normalization_context"={"groups"={"squad", "squad:user", "user"}},
     * "denormalization_context"={"groups"={"squad", "squad:user"}}
     * })
     */
    class Squad
    {
    
    ...
    
    /**
     * ...
     * @Groups("squad")
     */
    private $name;
    
    /**
     * ...
     * @Groups("squad:user")
     */
    private $users;
    
    ...
    class User
    {
    
     /**
      * ...
      * @Groups("user")
      */
     private $username;
    ...