php - 如何在 apiplatform/graphql 上创建/突变具有子关系的实体
问题描述
我想创建两个相关的实体。如何创建具有所需子实体的第一个实体。
我尝试了以下代码,但 graphql 返回以下错误:
{
"errors": [
{
"message": "Variable \"$stock\" of type \"createProductInput!\" used in position expecting type \"String\".",
"extensions": {
"category": "graphql"
},
"locations": [
{
"line": 7,
"column": 3
},
{
"line": 15,
"column": 17
}
]
}
]
}
突变:
mutation createProduct ($input: createProductInput!) {
createProduct(input: $input) {
clientMutationId
product {
uuid
name
sku
}
}
}
变量:
{
"input": {
"name": "ProductAAA",
"sku": "product_aaa",
"stock": {
"quantity": 33,
"unit": "s"
}
}
}
奇怪的是 createProductInput 说 stock 是一个字符串而不是一个对象。
uuid: String!
name: String!
sku: String!
stock: String
clientMutationId: String
这些是我的实体:
// Product.php
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Annotation\ApiSubresource;
use Doctrine\ORM\Mapping as ORM;
/**
* @ApiResource
* @ApiFilter(ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter::class, properties={"name": "partial", "sku": "partial"})
*
* @ORM\Table(name="products")
*/
class Product
{
/**
* @ORM\Id
* @ORM\Column(name="product_id", type="uuid", unique=true)
* @ORM\GeneratedValue(strategy="CUSTOM")
* @ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")
*
* @ApiProperty(identifier=true)
*/
private $id;
/**
* @ORM\Column(type="string")
*/
private $name;
/**
* @ORM\Column(type="string")
*/
private $sku;
/**
* @ORM\ManyToOne(targetEntity="Stock", cascade={"PERSIST"})
* @ORM\JoinColumn(name="stock_id", referencedColumnName="stock_id")
*
* @ApiSubresource
*/
private $stock;
}
// Stock.php
use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
/**
* @ApiResource
*
* @ORM\Table(name="stocks")
*/
class Stock
{
/**
* @ORM\Id
* @ORM\Column(name="stock_id", type="uuid", unique=true)
* @ORM\GeneratedValue(strategy="CUSTOM")
* @ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")
*
* @ApiProperty(identifier=true)
*/
private $id;
/**
* @ORM\Column(type="string")
*/
private $quantity;
/**
* @ORM\Column(type="string")
*/
private $unit;
}
解决方案
您不能在突变中创建嵌套实体,您需要先创建嵌套实体,然后在突变中使用其 IRI。这就是类型为String的原因。
以前是可能的,但已被删除,因为它导致了一些问题。见:https ://github.com/api-platform/core/pull/1886
推荐阅读
- database - 埃菲尔:转义字符
- ios - 跨不同模拟器打印视图的 bounds.width 属性时的常量值 od 375
- selenium - 使用 PageFactory [Selenium] 指定超时
- laravel - 调用未定义的方法 stdClass::links()
- facebook - 通过 Facebook Messenger 分享链接 - react-native android
- html - 如何将网站部署到 Apache 服务器?
- sql-server - 如何将代码优先迁移应用到 Azure 中的数据库?
- javascript - JavaScript for 循环在调用 AJAX 调用时返回“干净”
- c# - Convert.ToInt32(nullableVariable) VS nullableVariable.GetValueOrDefault()
- ios - 如何在 swift 中获得 tableviewcell 中的圆形 UIbutton?