rest - 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/squads
where "users": [1,2,3]
1, 2, 3 是现有用户的 id 并将它们链接到创建的Squad
实体。这可以使用来自 api-platform 的一些默认注释吗?或者我该怎么做?
解决方案
对于 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;
...
推荐阅读
- python - Pandas df 根据与不同列中的行匹配的字典中的值更改一列中的行的值
- java - 如何使用两个类获得两个变量的总和
- javascript - 使用正则表达式从 XML 中提取字符串
- django - 在 DRF 创建表单上添加 Django 传单位置选择器
- python - 如何增加 axs[i].title.set_text 上的标题字体大小
- ios - SwiftUI:iPad 弹出框上奇怪的关闭动画
- javascript - 在不丢失原始堆栈的情况下覆盖 console.log 方法 - javascript
- struct - LLVM 后端如何处理具有动态访问权限的结构的 getelementptr?
- cryptography - 无法将 pkcs11-tool 与自定义 hsm 角色一起使用
- automation - 我正在尝试使用 7-zip 和 AutoHotKey 提取文件夹,但脚本仅在新窗口中打开压缩文件夹