首页 > 解决方案 > API平台相关的资源创建实体

问题描述

有没有办法在实体创建资源上传递已经创建的相关实体的 ID 数组?默认文档说有关在发布请求时创建所有内容。一些数据。我有Squad实体:

/**
 * @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;

User实体:

/**
 * @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;

我想要实现的主要目标是发送POST /api/squadswhere "users": [1,2,3]1, 2, 3 是现有用户的 id 并将它们链接到创建的Squad实体。这可以使用来自 api-platform 的一些默认注释吗?或者我该怎么做?

标签: restsymfonyapi-platform.comsymfony-flex

解决方案


对于 JSON-LD,您可以像这样使用 IRI:

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

请记住,如果您在用户资源中禁用 GET 项目操作,这将不起作用。

您还可以强制执行此操作并禁用嵌入数据,以通过排除所有用户字段组来防止您的客户创建新用户。

/**
 * @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;
...

推荐阅读